简体   繁体   English

JAVA:当选择了jTextField时,在“ enter”按键上激活jFrameButton

[英]JAVA: Activating a jFrameButton on “enter” key press when a jTextField is selected

I have a program with a JFrame GUI and I want a button to be clicked when the user hits the Enter key from within a JTextField . 我有一个带有JFrame GUI的程序,我希望当用户从JTextField内按下Enter键时单击一个按钮。 Yes I have tried 是的,我尝试过

rootPane.setDefaultButton(jButton5);

but it only works when the text field isn't selected. 但仅在未选择文本字段时才有效。 How could I have it click the button when the text field is selected? 选择文本字段后,如何单击按钮?

Thank you in advance :D 预先谢谢你:D

JTextField.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){

                    jButton5.doClick();

            }});

JTextField is you text field component. JTextField是您的文本字段组件。 Then when you click the enter key, doClick method of JButton is invoked which Programmatically perform a "click". 然后,当您单击Enter键时,将调用JButton的doClick方法,该方法以编程方式执行“单击”。 This does the same thing as if the user had pressed and released the button. 这与用户按下并释放按钮的作用相同。

You'll have to add actionListener to textField and override method actionPerformed() 您必须将actionListener添加到textField并重写方法actionPerformed()

text.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Text=" + text.getText());
        //Your logic
      }
});

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

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