How to Modify the default editing behavior of a TreeCellEditor (Java)
I have a custom object that has a description (String) and priority value (int). I display these values in a JTree because t开发者_运维百科here is a hierarchical relationship between different objects of this type. I only display the description in the JTree nodes because the priority is not important for display purposes.
I would like to have a JDialog pop-up when I edit a JTree node (leaf or node) - for example by pressing F2. This dialog will then be used to edit both the description and the priority.
How do I prevent the JTree from performing the default editing of the text as a text field and call up the custom dialog instead?
An easy way I suppose would be to subclass the DefaultTreeCellEditor class and override the isCellEditable method. Then, I would invoke the JDialog there (I can obtain the relevant initialization elements when I instantiate the custom DefaultTreeCellEditor) and simply return false to prevent the default editing - but this to me doesn't seem elegant enough.
As an alternative, consider org.netbeans.swing.outline.Outline
, discussed further here.
I suppose F2 works on your tree nodes because you called JTree#setEditable(true)
.
F2 binding is installed in BasicTreeUI#installKeyboardActions
. You can install your own binding in the usual way:
JTree tree = new JTree(new String[]{"a", "b", "c"});
tree.setEditable(true);
InputMap m = tree.getInputMap(JComponent.WHEN_FOCUSED);
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
m.put(ks, "actionMapKey");
tree.getActionMap().put("actionMapKey", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
// do your stuff
}
});
JComponent.WHEN_IN_FOCUSED_WINDOW
is usually preferable over JComponent.WHEN_FOCUSED
but BasicTreeUI uses the latter.
If you want to use a different key, it's a bit tricky to remove the F2 binding as it's in the parent input map:
m.remove(ks);
if( m.getParent() != null )
m.getParent().remove(ks);
精彩评论