Search code examples
javaswingjtree

How do I change the "root" directories name in JTree?


I have a simple implementation of JTree:

tree1 = new JTree(LibObj.collectionToStringArray(LibObj.books));
tree1.setRootVisible(true);
scrollPane2 = new JScrollPane(tree1);
scrollPane2.setPreferredSize(new Dimension(350, 300));
panel.add(scrollPane2);

LibObj.collectionToStringArray(LibObj.books) is a method in another class that takes a collection and turns it into an array of strings

Everything is displaying as expected but the root directory is named "Root". How do I change the name? (I want it to be called Books)


Solution

  • Using the constructor JTree(TreeNode node) would give you the chance to create your own root node.

    Just like this:

    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node name");
    for( String book : booksArray ) {
        DefaultMutableTreeNode bookNode = new DefaultMutableTreeNode(book);
        rootNode.add(bookNode);
    }
    
    tree1 = new JTree(rootNode);
    tree1.setRootVisible(true);
    [...]