简体   繁体   中英

How to edit a JTree node with a single-click

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM