Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...

Swing Chapter 17. (Advanced topics) Trees. Easy for reading, Click here!

Custom Search
Swing Chapter 17. (Advanced topics) Trees. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 2/7 

Previous Page Previous Page (1/7) - Next Page (3/7) Next Page
Subpages: 1. JTree 
Basic JTree example 
Directories tree: part I - Dynamic node retrieval 
4. Directories tree: part II - Popup menus and programmatic navigation 
5. Directories tree: part III - Tooltips 
6. JTree and XML documents 
7. Custom editors and renderers 

17.2  Basic JTree example - network object IDs

As we know very well by now, JTree is suitable for the display and editing of a hierarchical set of objects. To demonstrate this in an introductory-level example, we will consider a set of Object Identifiers (OIDs) used in the Simple Network Management Protocol (SNMP). In the following example, we show how to build a simple JTree displaying the initial portion of the OID tree.

SNMP is used extensively to manage network components, and is particularly important in managing internet routers and hosts. Every object managed by SNMP must have a unique OID. An OID is built from a sequence of numbers separated by periods. Objects are organized heirarchicaly and have an OID with a sequence of numbers equal in length to their level (see 17.1.1) in the OID tree. The International Organization of Standards (ISO) establishes rules for building OIDs.

Note that understanding SNMP is certainly not necessary to understand this example. The purpose is to show how to construct a tree using:

A DefaultTreeModel with DefaultMutableTreeNodes containing custom user objects.

A customized DefaultTreeCellRenerer.

A TreeSelectionListener which displays information in a status bar based on the TreePath encapsulated in the TreeSelectionEvents it receives.

Figure 17.2 JTree with custom cell renderer icons, selection listener, and visible root handles.

<<file figure17-2.gif>>

The Code: Tree1.java

see \Chapter17\1

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import javax.swing.*;

import javax.swing.tree.*;

import javax.swing.event.*;

public class Tree1 extends JFrame


  protected JTree  m_tree = null;

  protected DefaultTreeModel m_model = null;

  protected JTextField m_display;

  public Tree1() {

    super("Sample Tree [OID]");

    setSize(400, 300);

    Object[] nodes = new Object[5];

    DefaultMutableTreeNode top = new DefaultMutableTreeNode(

      new OidNode(1, "ISO"));

    DefaultMutableTreeNode parent = top;

      nodes[0] = top;

    DefaultMutableTreeNode node = new DefaultMutableTreeNode(

      new OidNode(0, "standard"));


    node = new DefaultMutableTreeNode(new OidNode(2,



    node = new DefaultMutableTreeNode(new OidNode(3, "org"));


    parent = node;

    nodes[1] = parent;

    node = new DefaultMutableTreeNode(new OidNode(6, "dod"));


    parent = node;

    nodes[2] = parent;

    node = new DefaultMutableTreeNode(new OidNode(1, "internet"));


    parent = node;

    nodes[3] = parent;

    node = new DefaultMutableTreeNode(new OidNode(1, "directory"));


    node = new DefaultMutableTreeNode(new OidNode(2, "mgmt"));


    nodes[4] = node;

    node.add(new DefaultMutableTreeNode(new OidNode(1, "mib-2")));

    node = new DefaultMutableTreeNode(new OidNode(3,



    node = new DefaultMutableTreeNode(new OidNode(4, "private"));

    node.add(new DefaultMutableTreeNode(new OidNode(1,



    node = new DefaultMutableTreeNode(new OidNode(5, "security"));


    node = new DefaultMutableTreeNode(new OidNode(6, "snmpV2"));


    node = new DefaultMutableTreeNode(new OidNode(7,



    m_model = new DefaultTreeModel(top);

    m_tree = new JTree(m_model);

    DefaultTreeCellRenderer renderer = new


    renderer.setOpenIcon(new ImageIcon("opened.gif"));

    renderer.setClosedIcon(new ImageIcon("closed.gif"));

    renderer.setLeafIcon(new ImageIcon("leaf.gif"));




    TreePath path = new TreePath(nodes);




    JScrollPane s = new JScrollPane();


    getContentPane().add(s, BorderLayout.CENTER);

    m_display = new JTextField();


    getContentPane().add(m_display, BorderLayout.SOUTH);

    WindowListener wndCloser = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {







  public static void main(String argv[]) {

    new Tree1();


  class OidSelectionListener implements TreeSelectionListener


    public void valueChanged(TreeSelectionEvent e) {

      TreePath path = e.getPath();

      Object[] nodes = path.getPath();

      String oid = "";

      for (int k=0; k<nodes.length; k++) {

        DefaultMutableTreeNode node =


        OidNode nd = (OidNode)node.getUserObject();

        oid += "."+nd.getId();






class OidNode


  protected int    m_id;

  protected String m_name;

  public OidNode(int id, String name) {

    m_id = id;

    m_name = name;


  public int getId() { return m_id; }

  public String getName() { return m_name; }

  public String toString() { return m_name; }


Understanding the Code

Class Tree1

This class extends JFrame to implement the frame container for our JTree. Three instance variables are declared:

JTree m_tree: our OID tree.

DefaultTreeModel m_model: tree model to manage data.

JTextField m_display: used as a status bar to display the selected object's OID.

The constructor first initializes the parent frame object. Then a number of DefaultMutableTreeNodes encapsulating OidNodes (see below) are created. These objects form a hierarchical structure with DefaultMutableTreeNode top at the root. Note that during the construction of these nodes, the Object[] nodes array is populated with a path of nodes leading to the "mgmt" node.

DefaultTreeModel m_model is created with the top node as the root, and JTree  m_tree is created to manage this model. Then some specific options are set for this tree component. First, we replace the default icons for opened, closed and leaf icons with our custom icons, using a DefaultTreeCellRenderer as our tree's cell renderer:

        DefaultTreeCellRenderer renderer = new


        renderer.setOpenIcon(new ImageIcon("opened.gif"));

        renderer.setClosedIcon(new ImageIcon("closed.gif"));

        renderer.setLeafIcon(new ImageIcon("leaf.gif"));


Then we set the showsRootHandles property to true, the Editable property to false, and select the path determined by the nodes array formed above:



        TreePath path = new TreePath(nodes);


Our custom OidSelectionListener (see below) TreeSelectionListener is added to the tree to receive notification when our tree's selection changes.

A JScrollPane is created to provide scrolling capabilities, and our tree is added to its JViewport. This JScrollPane is then added to the center of our frame. A non-editable JTextField m_display is created and added to the south region of our frame's content pane to display the currently selected OID.

Class Tree1.OidSelectionListener

This inner class implements the TreeSelectionListener interface to receive notifications about when our tree's selection changes. Our valueChanged() implementation extracts TreePath for the current selection and visits each node, starting from the root, accumulating the OID in .N.N.N form as it goes (where N is a digit). This method ends by displaying the resulting OID in our text field status bar.

Class OidNode

This class encapsulates a single object identifier as a number and a String name describing the associated object. Both values are passed to the OidNode constructor. Instances of this class are passed directly to the DefaultMutableTreeNode constructor to act as a node's user object. The overridden toString() method is used to return the name String so that our tree's cell renderer will display each node correctly. Recall that, by default, DefaultTreeCellRenderer will call a node's user object toString() method for rendering.

Running the Code

Figure 17.1 shows our OID tree in action. Try selecting various tree nodes and note how the selected OID is displayed at the bottom of the frame.

UI Guideline : Icons & Root Handles

In this example, we are visually re-inforcing the data hierarchy with icons. The icons are overloading on the root handles to communicate whether an element is a document or a container and whether that container is open or closed. The book icon has two variants to communicate "open book" and "closed book". The icons are communicating the same information as the root handles.
Therefore, it is technically possible to remove the root handles. In some problem domains, hidden root handles may be more appropriate, providing that the Users are comfortable with interpreting the book icons and realise that a "closed book" icon means that the node can be expanded.

[ Return to Swing (Book) ]

Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color

[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

[ More in News Section ]

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy