How to Create a JTree Component in Java
In Java, you use the JTree class to create a tree component that displays the nodes of a tree. In order to use it correctly, check out the key constructors and methods of this class.
|void JTree()||Creates an empty tree (not very useful, if you ask me).|
|void JTree(TreeNode root)||Creates a tree that displays the tree that starts at the
|Adds the specified listener to listen for tree-selection
|Gets the node that is currently selected.|
|Gets the selection model for the tree. See this section for
what you can do with the TreeSelectionModel object.
|Sets the number of rows visible in the display.|
The first step in creating a JTree component is declaring a JTree variable as a class instance variable so that you can access the constructor and other methods, as follows:
Then, in the frame constructor, you call the JTree constructor to create the tree component, passing the root node of the tree you want it to display as a parameter:
tree1 = new JTree(root);
By default, the user is allowed to select multiple nodes from the tree. To restrict the user to a single selection, use this strange incantation:
Here the getSelectionModel method is called to get a TreeSelectionModel object that determines how the user can select nodes in the tree. This class provides a method named setSelectionMode that lets you set the selection mode. To limit the tree to a single node selection, you must pass this method the TreeSelectionModel.SINGLE_TREE_SELECTION field.
You can control the size of the tree component by calling the setVisibleRowCount method, as in this example:
Here the tree is just large enough to show 12 rows at a time.
Finally, you add the tree component to a scroll pane so that the user can scroll the tree if it doesn’t fit in the space provided. Then you should add the scroll pane to a panel that is in turn added to the frame, like this:
JScrollPane scroll = new JScrollPane(tree1); panel1.add(scroll);