Java Swing Tutorial - Java Swing JTree








A JTree is used to display hierarchical data in a tree-like structure. Each item in a JTree is called a node.

A node is further categorized as a branch node or a leaf node.

A JTree uses a selection model to keep track of the selected nodes. The selection model is an instance of the TreeSelectionModel interface.

A JTree allows the user to select nodes in three different modes. They are represented by three constants defined in the TreeSelectionModel interface:

  • SINGLE_TREE_SELECTION selects only one node at a time.
  • CONTIGUOUS_TREE_SELECTION selects any number of contiguous nodes.
  • DISCONTIGUOUS_TREE_SELECTION selects any number of nodes without any restrictions.

The following code demonstrates how to use some of the methods of the selection model of a JTree:

TreeSelectionModel selectionModel  = tree.getSelectionModel();
selectionModel.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
int  selectedCount = selectionModel.getSelectionCount();
TreePath[] selectedPaths  = selectionModel.getSelectionPaths();

We can add a TreeSelectionListener to a JTree, which will be notified when a node is selected or deselected.

Create JTree from Vector

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
/*  w  w  w. j  a v  a2 s .com*/
public class Main extends JFrame {

  public static void main(String[] args) {
    Main stt = new Main();
    stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    stt.setSize(250, 250);
    stt.setVisible(true);
  }

  public Main() {
    Object[] genealogy = { "A", "B", "C", "D", "E", "F" };
    java.util.Vector v = new java.util.Vector() {
      public String toString() {
        return "DD";
      }
    };
    v.addElement("1");
    v.addElement("2");
    v.addElement("3");
    v.addElement("4");
    genealogy[0] = v;
    JTree tree = new JTree(genealogy);
    tree.setRootVisible(true);
    JScrollPane jsp = new JScrollPane(tree);
    getContentPane().add(jsp);
  }

}




Tree Node

import java.awt.BorderLayout;
/*from w w  w.  j  ava 2s.  c o  m*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
    root.insert(mercury, 0);
    DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
    root.insert(venus, 1);
    DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
    root.insert(mars, 2);
    JTree tree = new JTree(root);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}




Delete tree node

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
//from  w  ww. j a  v a2  s  . c  o  m
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class Main extends JFrame {

  protected JTree tree;

  public static void main(String[] args) {
    Main dn = new Main(new JTree());
    dn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    dn.setSize(400, 300);
    dn.setVisible(true);
  }

  public Main(JTree jt) {
    super();
    tree = jt;
    getContentPane().add(tree);
    tree.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent event) {
        if (((event.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
            && (tree.getSelectionCount() > 0)) {
          showMenu(event.getX(), event.getY());
        }
      }
    });
  }

  protected void showMenu(int x, int y) {
    JPopupMenu popup = new JPopupMenu();
    JMenuItem mi = new JMenuItem("Delete");
    TreePath path = tree.getSelectionPath();
    Object node = path.getLastPathComponent();
    if (node == tree.getModel().getRoot()) {
      mi.setEnabled(false);
    }
    popup.add(mi);
    mi.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        deleteSelectedItems();
      }
    });
    popup.show(tree, x, y);
  }

  protected void deleteSelectedItems() {
    DefaultMutableTreeNode node;
    DefaultTreeModel model = (DefaultTreeModel) (tree.getModel());
    TreePath[] paths = tree.getSelectionPaths();
    for (int i = 0; i < paths.length; i++) {
      node = (DefaultMutableTreeNode) (paths[i].getLastPathComponent());
      model.removeNodeFromParent(node);
    }
  }
}