【发布时间】:2021-08-30 04:23:23
【问题描述】:
我有一个像这张图片一样的登录表单。
登录按钮是一个带有图标的 JLabel。我希望能够按“ENTER”并登录。
我已将登录逻辑放入一个名为 doAction(); 的方法中;我在登录标签上有一个 MouseEvent,它按预期工作,并在我单击登录 Jlabel 时调用 doAction()。我希望每次按“ENTER”时都会发生同样的事情。我试过这个:
KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = login.getInputMap(condition);
ActionMap actionMap = login.getActionMap();
inputMap.put(keyStroke, keyStroke.toString());
actionMap.put(keyStroke.toString(), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
doAction();
}
});
问题是只有当我在密码字段中使用光标时这才有效。如果我在 usernameField 中使用光标,则它不起作用
【问题讨论】:
-
"登录按钮是一个带有图标的 JLabel。" .. 为什么? 或者更确切地说,为什么 不使用未修饰的
JButton和ActionListener?一般提示: 1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 例如,获取图像的一种方法是热链接到在this Q&A 中看到的图像。例如。 this answer 中的代码热链接到嵌入在this question 中的图像。
标签: java swing key-bindings keyevent