How to edit a JTree node with a single-click

邮差的信 提交于 2019-12-30 11:14:04

问题


I have a JTree, and would like for its getTreeCellEditorComponent() method to be invoked when I single click on a node. According to the documentation for the DefaultTreeCellEditor class (which I extended), "Editing is started on a triple mouse click, or after a click, pause, click and a delay of 1200 miliseconds." Is there some way to override this behavior, so that a single-click could start the editing process?


回答1:


The JTree API recommends a MouseListener, but a key binding is also handy. This example invokes startEditingAtPath() and binds to the Enter key:

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

Addendum: See also this answer regarding usability.




回答2:


Technically, you can subclass DefaultTreeCellEditor and tweaks its logic to start editing on the first single click:

JTree tree = new JTree();
tree.setEditable(true);
TreeCellEditor editor = 
        new DefaultTreeCellEditor(tree, (DefaultTreeCellRenderer) tree.getCellRenderer()) {
    @Override
    protected boolean canEditImmediately(EventObject event) {
        if((event instanceof MouseEvent) &&
           SwingUtilities.isLeftMouseButton((MouseEvent)event)) {
            MouseEvent       me = (MouseEvent)event;

            return ((me.getClickCount() >= 1) &&
                    inHitRegion(me.getX(), me.getY()));
        }
        return (event == null);
    }
};
tree.setCellEditor(editor);

There's a usability quirk, though, as now you can't select without starting an edit - which may or may not be your intention.



来源:https://stackoverflow.com/questions/15625424/how-to-edit-a-jtree-node-with-a-single-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!