简体   繁体   English

如何在Java中捕获Enter键并将事件更改为Tab

[英]How to catch Enter key and change event to Tab in Java

I have a swing application with multiple jtextfield on it. 我有一个带有多个jtextfield的swing应用程序。 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? 如何替换回车键的功能,当您按回车键时,它将像tab键一样转移到下一个可聚焦组件上? I dont want to put a keylistener on each jtextfield. 我不想在每个jtextfield上放置一个keylistener。

You're looking for Container.setFocusTraversalKeys : 您正在寻找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 . 有关更多信息,请查看Focus Subsystem教程

You can call: 您可以致电:

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

but you will have to register a single ActionListener with all your JTextFields. 但是您将必须在所有JTextField中注册一个ActionListener。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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