【发布时间】:2011-01-26 22:35:33
【问题描述】:
我怎样才能做到当我在 JTextField 中按下回车键时它会激活一个特定的 JButton?我的意思是类似于网页表单的内容,您可以在其中按 Enter 键来激活表单中的按钮。
【问题讨论】:
我怎样才能做到当我在 JTextField 中按下回车键时它会激活一个特定的 JButton?我的意思是类似于网页表单的内容,您可以在其中按 Enter 键来激活表单中的按钮。
【问题讨论】:
您应该使用Action 作为JButton:
Action sendAction = new AbstractAction("Send") {
public void actionPerformed(ActionEvent e) {
// do something
}
};
JButton button = new JButton(sendAction);
然后您可以为JTextField 或MenuItem 设置相同的操作,如果您希望菜单中提供相同的操作:
JTextField textField = new JTextField();
textField.setAction(sendAction);
【讨论】:
这样的事情应该可以工作:
textField.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
button.requestFocusInWindow();
}
});
【讨论】:
您可以通过将default 行为添加到按钮来实现这一点,就像这样
cmdLogin.setDefaultCapable(true); // by default, this is true
this.getRootPane().setDefaultButton(cmdLogin); // here `this` is your parent container
【讨论】:
default 行为。
我会做如下的事情:
textField.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
button.doClick();
}
}
});
}
【讨论】: