Why am I losing focus for a short time from JTree after editing Node?

try: F2 start editing and ENTER stop editing, and the focus will switch to the next Component and return to the Node Tree in milliseconds. In this example, you can see how the focusPainted rectangle lights up in the JTabbedPane header. With FocusListener it should be clearer.

Why am I losing focus for a short time from JTree after editing 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();
        }
    });
}
}
+3
source share
1 answer

DefaultCellEditor JTree . . (Enter ), BasicTreeUI.completeEditing() , . .

. , ( ). .

, , BasicTreeUI .

.

( , ) , FocusTraversalPolicy:

private static class TreeEditorFocusTraversalPolicy extends DefaultFocusTraversalPolicy {
    private final JTree tree;
    public TreeEditorFocusTraversalPolicy(JTree tree) {
        this.tree = tree;
    }

    @Override
    public Component getComponentAfter(Container aContainer, Component aComponent) {
        if (aComponent instanceof CellEditor) {
            return tree;
        }
        return super.getComponentAfter(aContainer, aComponent); 
    }
}

:

tree.setFocusTraversalPolicy(new TreeEditorFocusTraversalPolicy(tree));
tree.setFocusCycleRoot(true);

: (Tab, Shift + Tab) . FocusTraversalPolicy - Swing . , LegacyGlueFocusTraversalPolicy, .

, .

+2

Source: https://habr.com/ru/post/1792829/


All Articles