简体   繁体   中英

How to catch Enter key and change event to Tab in Java

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.

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 .

You can call:

KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.focusNextComponent();

but you will have to register a single ActionListener with all your JTextFields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM