Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: JTrees are a nightmare!

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default JTrees are a nightmare!

    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


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: JTrees are a nightmare!

    Hello Danjb,

    This code works perfectly

    Press F2 or double click the node, enter the new value and press enter. The new value remains!
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  3. #3
    Junior Member
    Join Date
    May 2011
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: JTrees are a nightmare!

    Wow, that's really weird... I could have sworn it didn't work the other day! Perhaps I was clicking on another node instead of pressing "Enter".

    I have a second problem, however, regarding sorting nodes:

    Whenever I add or rename a node, I want the nodes to remain sorted alphabetically; just to complicate things further, however, I have 2 types of node, "Files" and "Folders", and I want "Folders" to always come first.

    This is my sorting code, but I get some very strange results, such as disappearing nodes or even nodes showing up as just "...":

        /**
         * Sorts all the nodes in the tree
         * First by: "Folder" Status
         * Then: Alphabetically
         */
        public void sortNodes(TreeItem folder){
        	Enumeration<TreeItem> children = folder.children();
        	while (children.hasMoreElements()){
        		TreeItem node = children.nextElement();
        		sortNodes(node);
        		if (!node.isLeaf()) sortChildren(node);
        	}
        }
     
        /**
         * Sorts the children in a folder
         * First by: "Folder" Status
         * Then: Alphabetically
         * @param parent Folder TreeItem containing children
         */
        public void sortChildren(TreeItem parent){
        	ArrayList<TreeItem> folders = new ArrayList<TreeItem>();
    		ArrayList<TreeItem> files = new ArrayList<TreeItem>();
    		// Use Enumeration children()
    		for (int j = 0; j < parent.getChildCount(); j++){
    			TreeItem child = (TreeItem)parent.getChildAt(j);
    			if (child.isFolder()){
    				folders.add(child);
    			} else {
    				files.add(child);
    			}
    		}
    		Collections.sort(folders);
    		Collections.sort(files);
    		parent.removeAllChildren();
    		for (TreeItem child : folders){
    			parent.add(child);
    		}
    		for (TreeItem child : files){
    			parent.add(child);
    		}
        }

    Any help would be appreciated,

    Thanks,

    - Danjb

  4. #4
    Junior Member
    Join Date
    May 2011
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: JTrees are a nightmare!

    Does anyone know how I can fix this?

Similar Threads

  1. Drag and Drop in JTrees
    By helloworld922 in forum Java Swing Tutorials
    Replies: 4
    Last Post: March 21st, 2014, 11:16 AM
  2. Drag and Drop in JTrees
    By helloworld922 in forum AWT / Java Swing
    Replies: 2
    Last Post: January 19th, 2010, 11:51 PM