JTree
The JTree class displays items which are structured in a hierarchy. Each item is known as a node, and each node can contain other nodes as its "children". Like JList and JTable, the JTree uses an associated model object (a TreeModel) to provide its data. However, in many cases it is easier to make use of the convenience class DefaultMutableTreeNode to represent each node in the tree. Suppose you want to model some of the countries of the five continents and have them displayed in a tree:
You will need to import package javax.swing.tree
- Each item in the tree is an instance of
DefaultMutableTreeNode - One of these instances must be the root node, being the one at the top-level that gets assigned to the tree. Here, it is continents
- To each node you can add other nodes as its children, and therefore the node that contains one or more children is known as its parent
- The
JTreeshould be nested inside aJScrollPane
Run the application to see the following display:
You can expand or contract any node by clicking the small "handle" graphic to the left of any parent item. If you expand Europe and then UK the screen should look as follows:
- Note that you might get scrollbars appear when you expand the nodes: the above screen shot has adjusted the size of the window so that any scrollbars disappear