How to Write a Tree Expansion Listener : TreeExpandedListener « Swing Event « Java Tutorial






Two kinds of listeners report expansion and collapse occurrences: tree expansion listeners and tree-will-expand listeners.

How to Write a Tree Expansion Listener
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

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

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    root.add(new DefaultMutableTreeNode("A"));
    root.add(new DefaultMutableTreeNode("B"));
    root.add(new DefaultMutableTreeNode("C"));
    JTree tree = new JTree(root);

    TreeExpansionListener treeExpandListener = new TreeExpansionListener() {

      public void treeExpanded(TreeExpansionEvent event) {
        TreePath path = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        String data = node.getUserObject().toString();
        System.out.println("Expanded: " + data);
      }

      public void treeCollapsed(TreeExpansionEvent event) {
        TreePath path = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        String data = node.getUserObject().toString();
        System.out.println("Collapsed: " + data);
      }
    };

    tree.addTreeExpansionListener(treeExpandListener);

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

  }
}








15.36.TreeExpandedListener
15.36.1.How to Write a Tree Expansion ListenerHow to Write a Tree Expansion Listener
15.36.2.To find out when a tree node has been expanded or collapsed: TreeExpansionListener Interface and TreeExpansionEvent ClassTo find out when a tree node has been expanded or collapsed: TreeExpansionListener Interface and TreeExpansionEvent Class