TreeCellEditor在编辑单元格后执行Action

时间:2015-07-05 12:49:36

标签: java swing jtree

我想在CellEditor消失后执行一个动作。之后调用哪个方法,从哪里开始?

1 个答案:

答案 0 :(得分:0)

您必须通过向树JTree添加CellEditorListener来收听 tree.getCellEditor().addCellEditorListener(new CellEditorListener() { @Override public void editingStopped(ChangeEvent e) { System.out.println(((DefaultCellEditor)e.getSource()).getCellEditorValue()); } @Override public void editingCanceled(ChangeEvent e) { System.out.println(((DefaultCellEditor)e.getSource()).getCellEditorValue()); } }); 的CellEditor

  JFrame frame = new JFrame();

    //Mock data
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    for (int i = 1; i < 5; i++) {
        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Parent" + i);
        for (int j = 1; j < 5; j++) {
            parent.add(new DefaultMutableTreeNode("Child" + j));
        }
        root.add(parent);
    }

    DefaultTreeModel tmodel = new DefaultTreeModel(root);
    JTree tree = new JTree(tmodel);

    tree.setEditable(true);//To enable editing

    tree.getCellEditor().addCellEditorListener(new CellEditorListener() {

        @Override
        public void editingStopped(ChangeEvent e) {
            //add you code here
            System.out.println(((DefaultCellEditor) e.getSource()).getCellEditorValue());
        }

        @Override
        public void editingCanceled(ChangeEvent e) {
            //add you code here too
            System.out.println(((DefaultCellEditor) e.getSource()).getCellEditorValue());
        }
    });
    frame.add(new JScrollPane(tree));

    frame.setTitle("Tree Editor Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

完整示例

__iter__()