JavaHow to Use Trees in Java GUI Applications

How to Use Trees in Java GUI Applications

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In Java software development, a tree is a graphical structure that allows developers to visualize how a set of data has been organized. Trees are a Swing component that inherits from the JComponent class. A tree is basically a vertical structure that has rows, which are referred to as nodes. Each tree has a root node, and it may have nodes that have children in them.

A node that has (or can have) children is called a branch. A node that does not have children is called a leaf. In this programming tutorial, we will discuss how to create trees in Java.

Read: Top Online Training Courses to Learn Java

How to Create a Tree in Java

To create a tree, all developers need to do is instantiate the JTree class. Since a JTree is a JComponent, programmers need to add it to a top-level container (such as a frame) in order for it to appear on the screen.

JTree has a constructor which takes in an array of type Object. This argument defines the name of your nodes. The code example below demonstrates how JTree takes in a String array:

import javax.swing.*;
class Tree{
   public static void main(String args[]){
      JFrame frame = new JFrame("Collections");


      String[] branches = {"Sets", "Lists", "Queue"};
      JTree MyTree = new JTree(branches);


      frame.add(MyTree);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400,400);  
      frame.setVisible(true);
   }
}

Running this code outputs the following:

Java Tree tutorial

In cases where you do not provide an argument for the JTree constructor, your program will output the default/model tree structure in your JDK environment.

The Java Tree Expansion Listener

Developers may want to trigger certain actions when a user expands an application’s tree. For example, highlighting certain sections of the tree. The TreeExpansionListener interface allows you to achieve this functionality.

TreeExpansionListener has only two methods: treeCollapsed(TreeExpansionEvent event) and treeExpanded(TreeExpansionEvent event). These methods perform an action that you specify in their method body when a tree has been expanded or collapsed, respectively.

These two methods have one parameter of type TreeExpansionEvent. The TreeExpansionEvent is a subclass of EventObject. It has only a single method (getPath()), which returns an array for the event path. A path is an ordered sequence of branches beginning from the root node.

In the first code example, we did not include any branch nodes. In case you wish to create a tree with branches, you can instantiate the DefaultMutableTreeNode class. This class creates a tree node that can have children. Using its constructor, programmers can pass the name of the branch.

To add leaves to the branch, you will need to use the add method.

The code example below shows these concepts. It outputs a given message when you collapse or expand the Collection root node or the List branch:

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


import java.awt.*;
import java.awt.event.*;

class ExpandingTree implements TreeExpansionListener {

   ExpandingTree (){

       JFrame frame = new JFrame();  

       DefaultMutableTreeNode top = new DefaultMutableTreeNode("Collection");
       DefaultMutableTreeNode set = new DefaultMutableTreeNode("Set");
       DefaultMutableTreeNode list = new DefaultMutableTreeNode("List");
       DefaultMutableTreeNode queue = new DefaultMutableTreeNode("Queue");
       DefaultMutableTreeNode arraylist = new DefaultMutableTreeNode("ArrayList");
       DefaultMutableTreeNode linkedlist = new DefaultMutableTreeNode("Linked List");

       top.add(set);
       top.add(list);
       top.add(queue);

       list.add(arraylist);
       list.add(linkedlist);

       JTree tree = new JTree(top);
       tree.addTreeExpansionListener(this);

       frame.add(tree);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(400,400);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }

   public static void main(String args[]){

       new ExpandingTree();
    }

   public void treeCollapsed(TreeExpansionEvent e) {
       System.out.println("You collapsed the tree.");
   }
   public void treeExpanded(TreeExpansionEvent e){
       System.out.println("Path of the expanded tree: " + e.getPath());
   }
}

Running this code creates the following output:

Java Tree code examples

Read: Java Tools to Increase Productivity

Using the Java Tree Selection Listener

To listen for when a node selection on your tree changes, your application needs to implement the TreeSelectionListener. This interface has one method: valueChanged( TreeSelectionEvent event) ), which responds to a selection event.

The TreeSelectionListener takes in a TreeSelectionEvent argument, which gives various information about the selection event. Here are some useful methods for this event:

  • getNewLeadSelectionPath(): returns an array for the currently selected node
  • getOldLeadSelectionPath(): returns an array for the previously selected node

The Java code example below prints out the current path selection whenever a user selects a node:

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

public class TreeSelectionHandler implements TreeSelectionListener{

   JFrame frame = new JFrame();
  
   TreeSelectionHandler(){

       DefaultMutableTreeNode fruit = new DefaultMutableTreeNode("Fruit");
       DefaultMutableTreeNode citrus = new DefaultMutableTreeNode("Citrus");
       DefaultMutableTreeNode berry = new DefaultMutableTreeNode("Berry");

       fruit.add(citrus);
       fruit.add(berry);

       JTree tree = new JTree(fruit);

       tree.addTreeSelectionListener(this);

       frame.add(tree);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(375,450);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }

   public static void main(String args[]) {

       new TreeSelectionHandler();       
   }


   public void valueChanged(TreeSelectionEvent e) {
       System.out.println(e.getNewLeadSelectionPath());
   }
 }

Final Thoughts on Java Trees

In Java, a tree is a structure that enables developers to visualize the hierarchical organization of some information. A good example of this is a directory structure. After following through the examples in this programming tutorial, you should be able to confidently create trees for your graphical Java applications.

Read: Top Java Frameworks

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories