如何捕获JTree节点扩展事件

时间:2015-07-31 22:14:38

标签: java swing listener jtree expand

我在SWING JTree中寻求类似于SWT的方法 TreeNode.addListener(SWT.Expand,new Listener()... 我设法检查最后选择的节点以找到所选节点,但是我怎样才能找到哪个节点被扩展并以正确的方式处理它?<​​/ p>

1 个答案:

答案 0 :(得分:2)

使用(有趣的名字)TreeWillExpandListener

TreeWillExpandListener treeWillExpandListener = new TreeWillExpandListener() {
      public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent)
          throws ExpandVetoException {

        TreePath path = treeExpansionEvent.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

        //Print the name of the node if toString() was implemented
        String data = node.getUserObject().toString();
        System.out.println("WillCollapse: " + data);

      }

      public void treeWillExpand(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException {

        TreePath path = treeExpansionEvent.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

        //print the name of the node if toString was implemented  
        String data = node.getUserObject().toString();
        System.out.println("WillExpand: " + data);

      }
    };

tree.addTreeWillExpandListener(treeWillExpandListener);