views:

50

answers:

2

I have a custom object that has a description (String) and priority value (int). I display these values in a JTree because there 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.

+1  A: 

As an alternative, consider org.netbeans.swing.outline.Outline, discussed further here.

trashgod
I like what I see. It is very similar to the way GTK+ made their TreeView components. This way - you see all the relevant data and can edit it. Displaying the priority in my problem isn't necessary, but doesn't detract from the solution. I will investigate further, thanks.
Mr Rho
+1  A: 

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);
Geoffrey Zheng