Chapter: Java The Complete Reference - Introducing GUI Programming with Swing - Exploring Swing

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Trees - Swing

A tree is a component that presents a hierarchical view of data. The user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class.


A tree is a component that presents a hierarchical view of data. The user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class. A sampling of its constructors is shown here:


JTree(Object obj [ ]) JTree(Vector<?> v) JTree(TreeNode tn)


In the first form, the tree is constructed from the elements in the array obj. The second form constructs the tree from the elements of vector v. In the third form, the tree whose root node is specified by tn specifies the tree.


Although JTree is packaged in javax.swing, its support classes and interfaces are packaged in javax.swing.tree. This is because the number of classes and interfaces needed to support JTree is quite large.

JTree relies on two models: TreeModel and TreeSelectionModel. A JTree generates a variety of events, but three relate specifically to trees: TreeExpansionEvent, TreeSelectionEvent, and TreeModelEvent. TreeExpansionEvent events occur when a node is expanded or collapsed. A TreeSelectionEvent is generated when the user selects or deselects a node within the tree. A TreeModelEvent is fired when the data or structure of the tree changes. The listeners for these events are TreeExpansionListener, TreeSelectionListener, and

TreeModelListener, respectively. The tree event classes and listener interfaces are packaged in javax.swing.event.

The event handled by the sample program shown in this section is TreeSelectionEvent. To listen for this event, implement TreeSelectionListener. It defines only one method, called valueChanged( ), which receives the TreeSelectionEvent object. You can obtain

the path to the selected object by calling getPath( ), shown here, on the event object:

TreePath getPath( )

It returns a TreePath object that describes the path to the changed node. The TreePath class encapsulates information about a path to a particular node in a tree. It provides several constructors and methods. In this book, only the toString( ) method is used. It returns a string that describes the path.

The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node.

The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here:


DefaultMutableTreeNode(Object obj)


Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children.


To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here:


void add(MutableTreeNode child)


Here, child is a mutable tree node that is to be added as a child to the current node. JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically


placed within a JScrollPane. This way, a large tree can be scrolled through a smaller viewport. Here are the steps to follow to use a tree:


            Create an instance of JTree.


            Create a JScrollPane and specify the tree as the object to be scrolled.


            Add the tree to the scroll pane.


            Add the scroll pane to the content pane.


The following example illustrates how to create a tree and handle selections. The program creates a DefaultMutableTreeNode instance labeled "Options". This is the top node of the tree hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll pane is then added to the content pane. Next, a label is created and added to the content pane. The tree selection is displayed in this label. To receive selection events from the tree, a TreeSelectionListener is registered for the tree. Inside the valueChanged( ) method, the path to the current selection is obtained and displayed.



// Demonstrate JTree.

import java.awt.*;


import javax.swing.event.*; import javax.swing.*; import javax.swing.tree.*; /*


<applet code="JTreeDemo" width=400 height=200> </applet>



public class JTreeDemo extends JApplet { JTree tree;


JLabel jlab;


public void init() { try {


SwingUtilities.invokeAndWait( new Runnable() {


public void run() { makeGUI();








} catch (Exception exc) {


System.out.println("Can't create because of " + exc);






private void makeGUI() {


// Create top node of tree.


DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");


// Create subtree of "A".


DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a);


DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1);


DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2);


// Create subtree of "B"


DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b);


DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1);


DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2);


DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3);


     //Create the tree.

     tree = new JTree(top);


     //Add the tree to a scroll pane.


     JScrollPane jsp = new JScrollPane(tree);


     //Add the scroll pane to the content pane.




     //Add the label to the content pane.


jlab = new JLabel(); add(jlab, BorderLayout.SOUTH);


// Handle tree selection events.

tree.addTreeSelectionListener(new TreeSelectionListener() {


public void valueChanged(TreeSelectionEvent tse) { jlab.setText("Selection is " + tse.getPath());










Output from the tree example is shown here:

The string presented in the text field describes the path from the top tree node to the selected node.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.