Reputation: 838
I have a swing application with multiple jtextfield on it. How do you replace the function of the enter key wherein when you press the Enter key, it will transfer to the nextfocusable component just like the tab key? I dont want to put a keylistener on each jtextfield.
Upvotes: 2
Views: 1801
Reputation: 44808
You're looking for Container.setFocusTraversalKeys
:
Container root = ...
// pressed TAB, control pressed TAB
Set<AWTKeyStroke> defaultKeys = root.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
// since defaultKeys is unmodifiable
Set<AWTKeyStroke> newKeys = new HashSet<>(defaultKeys);
newKeys.add(KeyStroke.getKeyStroke("pressed ENTER"));
root.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newKeys);
For more information, take a look at the Focus Subsystem tutorial.
Upvotes: 5
Reputation: 159754
You can call:
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.focusNextComponent();
but you will have to register a single ActionListener with all your JTextFields.
Upvotes: 2