Java Tutorial/Swing Event/TreeExpandedListener

Материал из Java эксперт
Перейти к: навигация, поиск

How to Write a Tree Expansion Listener

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



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);
  }
}





To find out when a tree node has been expanded or collapsed: TreeExpansionListener Interface and TreeExpansionEvent Class

public interface TreeExpansionListener implements EventListener {
      public void treeCollapse(TreeExpansionEvent treeExpansionEvent);
      public void treeExpand(TreeExpansionEvent treeExpansionEvent);
  }