Home » Java » java – How to show only root in JTree?-Exceptionshub

java – How to show only root in JTree?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a JTree like this:

private TreeNode createNodes() {

        DefaultMutableTreeNode root;
        DefaultMutableTreeNode grandparent;
        DefaultMutableTreeNode parent;

        root = new DefaultMutableTreeNode("San Francisco");

        grandparent = new DefaultMutableTreeNode("Potrero Hill");
        root.add(grandparent);

        parent = new DefaultMutableTreeNode("Restaurants");
        grandparent.add(parent);

        dummyParent = root;

        return root;
    }

I want to show only the root “San Francisco” in the screen not by default. Then the tree only expands when I click to the extended icon. How can I do that? I had tried to use some methods:

         tree.setRootVisible(true);
         tree.setShowsRootHandles(false);
How to&Answers:

I want to show only the root “San Francisco” in the screen

After you have created the data and added the model to the tree you can use:

tree.collapseRow(0);