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

时间:2012-08-19 00:24:18

标签: java swing keylistener

我有一个带有多个jtextfield的swing应用程序。如何替换回车键的功能,当按下回车键时,它将像标签键一样转移到下一个可聚焦组件?我不想在每个jtextfield上放置一个keylistener。

2 个答案:

答案 0 :(得分:5)

您正在寻找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);

有关详细信息,请查看Focus Subsystem tutorial

答案 1 :(得分:2)

您可以致电:

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

但您必须为所有JTextField注册一个ActionListener。