Create a JTree object and handle tree node selection event - Java Swing

Java examples for Swing:JTree

Description

Create a JTree object and handle tree node selection event

Demo Code

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

public class Main extends JFrame {
  public static void main(String[] args) {
    new Main();//from   w w  w  . j a  va2  s.c o  m
  }

  private JTree tree1;
  private JLabel showName;
  private DefaultTreeModel model;

  public Main() {
    this.setSize(225, 325);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel1 = new JPanel();

    DefaultMutableTreeNode root, andy, archie, happy, george, maude;

    root = new DefaultMutableTreeNode("Famous Spinoffs");

    andy = makeShow("The Andy Griffith Show", root);
    makeShow("A", andy);
    makeShow("B", andy);

    archie = makeShow("C", root);
    george = makeShow("D", archie);
    makeShow("E", george);
    maude = makeShow("F", archie);
    makeShow("G", maude);
    makeShow("H", archie);
    makeShow("I", archie);

    happy = makeShow("J", root);
    makeShow("K", happy);
    makeShow("L", happy);
    makeShow("M", happy);

    tree1 = new JTree(root);

    tree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree1.setVisibleRowCount(12);
    tree1.addTreeSelectionListener(new TreeListener());

    JScrollPane scroll = new JScrollPane(tree1);
    panel1.add(scroll);

    showName = new JLabel();
    panel1.add(showName);

    this.add(panel1);
    this.setVisible(true);
  }

  private DefaultMutableTreeNode makeShow(String title, DefaultMutableTreeNode parent) {
    DefaultMutableTreeNode show;
    show = new DefaultMutableTreeNode(title);
    parent.add(show);
    return show;
  }

  private class TreeListener implements TreeSelectionListener {
    public void valueChanged(TreeSelectionEvent e) {
      Object o = tree1.getLastSelectedPathComponent();
      DefaultMutableTreeNode show;
      show = (DefaultMutableTreeNode) o;
      String title = (String) show.getUserObject();
      showName.setText(title);
    }
  }
}

Related Tutorials