编程语言
首页 > 编程语言> > java – 如何通过单击编辑JTree节点

java – 如何通过单击编辑JTree节点

作者:互联网

我有一个JTree,并希望在我单击一个节点时调用它的getTreeCellEditorComponent()方法.根据DefaultTreeCellEditor类(我扩展)的文档,“编辑是在三次鼠标点击,或点击,暂停,点击和1200毫秒的延迟后开始的.”有没有办法覆盖此行为,以便单击可以启动编辑过程?

解决方法:

JTree API推荐使用MouseListener,但是键绑定也很方便.此示例调用startEditingAtPath()并绑定到Enter键:

final JTree tree = new JTree();
tree.setEditable(true);
MouseListener ml = new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        int row = tree.getRowForLocation(e.getX(), e.getY());
        TreePath path = tree.getPathForLocation(e.getX(), e.getY());
        if (row != -1) {
            if (e.getClickCount() == 1) {
                tree.startEditingAtPath(path);
            }
        }
    }
};
tree.addMouseListener(ml);
tree.getInputMap().put(
    KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "startEditing");

附录:另见answer关于可用性.

标签:jtree,java,swing
来源: https://codeday.me/bug/20191008/1875405.html