Hi,
I've been messing around with JTrees recently and I'm finding it rather difficult to get them to work the way I want. Firstly is to do with being able to rename nodes; I had it working at one point but not anymore.
Here is a very simplified example of the problem:
package gui; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeSelectionModel; public class TreeFrame extends JFrame implements TreeModelListener { public TreeFrame() { setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode( "Root Node"); rootNode.add(new DefaultMutableTreeNode("1")); rootNode.add(new DefaultMutableTreeNode("2")); rootNode.add(new DefaultMutableTreeNode("3")); DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); treeModel.addTreeModelListener(this); JTree tree = new JTree(treeModel); tree.setEditable(true); tree.setShowsRootHandles(true); add(tree); setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.out.println("Failed to load system look and feel."); } TreeFrame frame = new TreeFrame(); } public void treeNodesChanged(TreeModelEvent e) { DefaultMutableTreeNode node; node = (DefaultMutableTreeNode) (e.getTreePath().getLastPathComponent()); /* * If the event lists children, then the changed node is the child of * the node we have already gotten. Otherwise, the changed node and the * specified node are the same. */ try { int index = e.getChildIndices()[0]; node = (DefaultMutableTreeNode) (node.getChildAt(index)); } catch (NullPointerException exc) { } System.out.println("The user has finished editing the node."); System.out.println("New value: " + node.getUserObject()); } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } }
Most of this is taken straight from Oracle's "How to Use Trees" guide. But basically this demonstrates the problem - click on a node, press "F2" and you can type in a name, but the name doesn't stay!
Does anyone know how to fix this so the nodes can be properly renamed?
Thanks,
- Danjb