Java Swing: how to call stopCellEditing () before TreeListeners: valueChanged?

This is a continuation of these early questions:

When I use the property terminateEditOnFocusLostas shown below, my CellEditor stops editing correctly when the table loses focus:

jtable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

It also works with my JButtons. The method stopCellEditing()is called for my TableCellEditor before the button click action is processed. But when I use it with JTree, and the tree selection changes, the method TreeSelectionListener.valueChangedis called before stopCellEditing().

Does anyone know if there is a way to force a call stopCellEditing(), or should I just come up with some problem for this problem?

+2
source share
2 answers

JTreedoes not have a similar client property Swing. However JXTree, a derived class from JTreein SwingXmaking: invokeStopEditing.

If you cannot use it SwingX, you can always look at the source code JXTreeand see how this StopEditing mechanism works:JXTree SwingX 1.0 API Documentation and Javadoc (go to Source tab)

Specifically, starting from the line 974, a listener is created to track changes in the property " permanentFocusOwner" on KeyboardFocusManager, etc.

+1
source

, TreeSelectionListener stopCellEditing(). TreeCellEditor? , .

, JTable, . , JTree...


, JTree "terminateEditOnFocusLost" . , .

JTable, . , , JTree , , , stopEditing(), , cancelEditing(). , :

class CellEditorRemover implements PropertyChangeListener {
    KeyboardFocusManager focusManager;
    public CellEditorRemover(KeyboardFocusManager fm) {
        this.focusManager = fm;
    }

    public void propertyChange(PropertyChangeEvent ev) {
        if (!tree.isEditing() || 
          tree.getClientProperty("terminateEditOnFocusLost") != Boolean.TRUE) 
        {
          return;
        }

        Component c = focusManager.getPermanentFocusOwner();
        while (c != null) {
            if (c == tree) { // focus remains inside the tree
                return;
            } else if ((c instanceof Window)
                        || (c instanceof Applet && c.getParent() == null)) 
            {
                if (c == SwingUtilities.getRoot(tree)) {
                    if (!tree.getCellEditor().stopCellEditing()) {
                        tree.getCellEditor().cancelCellEditing();
                    }
                }
                break;
            }
            c = c.getParent();
        }
    }
}

, - . :

tree.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
KeyboardFocusManager fm = 
                KeyboardFocusManager.getCurrentKeyboardFocusManager();
editorRemover = new CellEditorRemover(fm);
fm.addPropertyChangeListener("permanentFocusOwner", editorRemover);

, , JTree , JTable, JButton.

0

All Articles