try: F2 start editing and ENTER stop editing and the focus switches to the next Component and goes back to the Tree-Node in milliseconds. In the example you can see the focusPainted rectangle flashing in the JTabbedPane-Header. With a FocusListener it shall be clearer.
Why I lose the focus for a short Time from JTree after editing a Node?
How to prevent this behavior?
public class Focus {
private static void createAndShowGUI() {
final JTextArea text = new JTextArea("Tab Header gained focus");
JTree tree = new JTree();
tree.setEditable( true );
int row = 0;
while( row < tree.getRowCount() ) {
tree.expandRow( row++ );
}
JTabbedPane tabp = new JTabbedPane();
tabp.addTab( "Lorem", text );
tabp.addFocusListener( new FocusListener() {
@Override
public void focusLost( FocusEvent e ) { }
@Override
public void focusGained( FocusEvent e ) {
text.setText( text.getText() +"\nWoohoo, I got the focus!" );
}
});
JFrame frame = new JFrame( "Focus" );
frame.setLayout( new BorderLayout() );
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(tree, BorderLayout.WEST);
frame.getContentPane().add(tabp, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
tree.startEditingAtPath( tree.getPathForRow( 0 ) );
}
public static void main(String[] x) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
}
The tree adds a DefaultCellEditor to the JTree hierarchy when editing starts. This textfield gains the focus. When editing stopped (Enter pressed), the BasicTreeUI.completeEditing() method checks whether the tree itself or the editor component is the focus owner. In that case, the tree will be focused again after the editing is finished.
In the stop algorithm, the editor is removed from the tree. It was the focus owner before, so the focus will be transfered to the next focusable component (focus cycle). In your UI this will be the tabbed pane.
Due to the fact that the editor was focused before, the BasicTreeUI requests the focus for the tree.
These steps map perfectly on your described behaviour.
The only solution (not complete, but shows the direction) is to set your own FocusTraversalPolicy:
Set this instance to your tree:
The problem so far: the focus traversal (Tab, Shift+Tab) does not work anymore. The FocusTraversalPolicy is a huge part of Swing and needs some time to create a working policy. Maybe have a look at the LegacyGlueFocusTraversalPolicy which is the default policy.
Hope this helps to get further.