What I want to happen is while editing JTree, I want to commit the edit if I click outside of the edit box.
tree.setInvokesStopCellEditing(true);
helped, where if I click somewhere in the JTree, the edit gets committed. However if I click outside of the JTree, like say a JTextPane the edit won't commit. Thus the Question: Question: How do I make JTree stop cell editing, when Focus Lost? Or When Left Click outside JTree Location? Also is there a prefered way to do this?
Note: In the code below I tried to solve this using a Focus Listener Annoymous inner class, and tried pseudocode WhenTreeLosesFocus() { if( tree.isEditing() ) tree.stopEditing(); }
That doesn't work because On Edit the Focus changes to a CellEditor component within the Tree, and I see the edit box flash on and then flash off quickly.
The solution doesn't have to be Focus based, it can be left click outside JTree area.
SSCE follows (BTW if you run the code for Convienence both Spacebar and F2 will rename nodes.)
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.KeyStroke;
public class StackExchangeQuestion3 {
public static void main(String[] args){
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setTitle("Stack Exchange Question");
window.setSize(400,500);//variable parameters would be best
window.setVisible(true);
JSplitPane split = new JSplitPane();
window.getRootPane().setContentPane(split);
JScrollPane left = new JScrollPane();
JScrollPane right = new JScrollPane();
JTree tree = new JTree();//loads sample tree data
tree.setEditable(true);//select a node then press F2 to edit (built in keybinding)
tree.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "startEditing");//can edit with space now
tree.setInvokesStopCellEditing(true);//this helps stop editing within focus of tree
JTextPane text = new JTextPane();
split.setLeftComponent(left);
split.setRightComponent(right);
left.setViewportView(tree);
right.setViewportView(text);
split.setDividerLocation(200);
tree.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) { }
public void focusLost(FocusEvent e) {
JTree tree = (JTree)e.getSource();
if( tree.isEditing() ) tree.stopEditing();
}
});//end addFocusListener
}//end main
}
Commentary with reasoning on if 1 way is preferred over the other is welcome. As well as Tips on how to Detect if Mouse Click outside of JTree/tips in the right direction.