我有JTree
,并且希望在单击某个节点时调用其getTreeCellEditorComponent()
方法。根据{{1}}类(我扩展)的文档,“编辑是通过三次鼠标点击,或点击,暂停,点击和1200毫秒的延迟后开始的。”有没有办法覆盖这种行为,以便单击可以开始编辑过程?
答案 0 :(得分:5)
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关于可用性的内容。
答案 1 :(得分:4)
从技术上讲,您可以将DefaultTreeCellEditor子类化并调整其逻辑,以便在第一次单击时开始编辑:
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);
但是,有一个可用性的怪癖,因为现在你不能在没有开始编辑的情况下选择 - 这可能是你的意图,也可能不是。