Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Dynamic JTrees (Controlling Root Node Visibility)

Tags:

java

swing

jtree

I have a question about how to dynamically generate JTrees. Is there a way to set the Root Node invisible without making its children invisible too? I have tried to do the following but it shows all nodes as invisible. Keep in mind that I want to add and remove children of the Root Node at any point in time. I've added comments so you can follow what I intend to do. Let me know if they are doing something I dont need, as I am new to JTrees and don't know the conventions. I would also like to be able to select multiple children for the listener.

    DefaultMutableTreeNode rootNode;
    rootNode = new DefaultMutableTreeNode(); //I want this invisible.

    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree tree = new JTree(treeModel);

    treeModel.addTreeModelListener(this);
    tree.setRootVisible(false); // Sets everything invisible
    tree.setEditable(true); //makes tree dynamic
    tree.setShowsRootHandles(true); //supposedly allows you to see the children of the nodes.

    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); 
    //I would like the line above to be multi-select; however, this doesn't seem to be an option.

    DefaultMutableTreeNode table = new DefaultMutableTreeNode( "table1");
    rootNode.add(book);

    DefaultMutableTreeNode value = new DefaultMutableTreeNode( "value");
    table.add(value);

In the above example. Nothing is shown and when I remove the "tree.setRootVisible(false)" everything is visible including the node.

like image 214
Jeffrey Avatar asked Dec 29 '22 07:12

Jeffrey


2 Answers

A very late answer, but I have just had the same problem. Ensure to expand your root node, so that its children become visible :

yourTree.expandPath(new TreePath(root.getPath()))
like image 195
Mouss Avatar answered Feb 11 '23 20:02

Mouss


I'd say the difference between the code in the question and in the TreeDemo is that the tree demo creates and adds all its nodes before creating the actual tree. If the nodes are to be added dynamically (after the tree is created) it should be done through the TreeModel. Otherwise no events saying the tree has changed will be generated. At least that is what the tutorial seems to say about editing the node's "content", might be the same issue:

Note that although DefaultMutableTreeNode has methods for changing a node's content, changes should go through the DefaultTreeModel cover methods. Otherwise, the tree model events would not be generated, and listeners such as the tree would not know about the updates.

Someone's solution

like image 33
Andreas Avatar answered Feb 11 '23 18:02

Andreas