按Enter键时,Java将焦点设置在jbutton上

时间:2011-01-26 22:35:34

标签: java swing focus jbutton

我怎样才能这样做,当我在JTextField中输入时,它会激活一个特定的JButton?我的意思是网页表单中的某些内容,您可以按Enter键激活表单中的按钮。感谢。

4 个答案:

答案 0 :(得分:13)

您应该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);

答案 1 :(得分:7)

这样的事情应该有效:

textField.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        button.requestFocusInWindow();
    }
});

答案 2 :(得分:4)

您可以通过向按钮添加default行为来实现此目的,例如

cmdLogin.setDefaultCapable(true); // by default, this is true
this.getRootPane().setDefaultButton(cmdLogin); // here `this` is your parent container

答案 3 :(得分:3)

我会做以下事情:

textField.addKeyListener(
  new KeyAdapter() {
     public void keyPressed(KeyEvent e) {
       if (e.getKeyCode() == KeyEvent.VK_ENTER) {
          button.doClick();
       }
     }
  });
}
相关问题