Listening for Expansion and Collapse Events in a JTree Component - Java Swing

Java examples for Swing:JTree

Description

Listening for Expansion and Collapse Events in a JTree Component

Demo Code


import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;

public class Main {
  public void m() throws Exception {
    JTree tree = new JTree();
    // Add pre-expansion event listener
    tree.addTreeWillExpandListener(new MyTreeWillExpandListener());

    // Add post-expansion event listener
    tree.addTreeExpansionListener(new MyTreeExpansionListener());
  }//w w w  .  jav a 2s.c om
}

class MyTreeWillExpandListener implements TreeWillExpandListener {
  public void treeWillExpand(TreeExpansionEvent evt) throws ExpandVetoException {
    JTree tree = (JTree) evt.getSource();

    // Get the path that will be expanded
    TreePath path = evt.getPath();

    // Cancel the operation if desired
    boolean veto = false;
    if (veto) {
      throw new ExpandVetoException(evt);
    }
  }

  public void treeWillCollapse(TreeExpansionEvent evt)
      throws ExpandVetoException {
    JTree tree = (JTree) evt.getSource();

    // Get the path that will be collapsed
    TreePath path = evt.getPath();

    // Cancel the operation if desired
    boolean veto = false;
    if (veto) {
      throw new ExpandVetoException(evt);
    }
  }
}

class MyTreeExpansionListener implements TreeExpansionListener {
  public void treeExpanded(TreeExpansionEvent evt) {
    JTree tree = (JTree) evt.getSource();
    // Get the expanded path
    TreePath path = evt.getPath();
  }

  public void treeCollapsed(TreeExpansionEvent evt) {
    JTree tree = (JTree) evt.getSource();

    // Get the path that was collapsed
    TreePath path = evt.getPath();
  }
}

Related Tutorials