简体   繁体   English

按钮单击相当于按回车键java

[英]Button click equivalent of pressing the enter key java

I have a button with variable name "btntry". 我有一个变量名为“btntry”的按钮。 When the user clicks this button I want it to perform the same action as would have been performed if the user pressed the enter key. 当用户单击此按钮时,我希望它执行与用户按下回车键时执行的操作相同的操作。 Is this possible? 这可能吗?

It would be helpful if you could tell me how to insert the code in this case: 如果您能告诉我如何在这种情况下插入代码,将会很有帮助:

This are the two methods I have 这是我的两种方法

private void btntryActionPerformed(java.awt.event.ActionEvent evt) {                                       
       // TODO add your handling code here:
}                                      

private void entryfieldActionPerformed(java.awt.event.ActionEvent evt) {                                           
char[] v = { 'c', 'e', 'n', 't', 'i', 'p', 'e', 'd', 'e' };
    char n;
    n = entryfield.getText().charAt(0);
        boolean flag = false;
    int index = 0;
    boolean flag2 = false;
    while (index < (v.length)) {
        if (n == (v[index])) {
            flag = true;
        } else {
            flag = false;
        }
        index++;
        if (flag == true){
            flag2 = true;
        }

    }
    if (flag2 == true) {
        System.out.println("Correct");
    } else {
        System.out.println("Wrong");
    }

I when the button is clicked I want the same effect as the enter key being pressed 单击按钮时,我想要按下输入键的效果

I when the button is clicked I want the same effect as the enter key being pressed 单击按钮时,我想要按下输入键的效果

You can make the button the default button for the frame: 您可以将按钮设置为框架的默认按钮:

frame.getRootPane().setDefaultButton( button );

Then when you use the Enter key the ActionListener of the button will be invoked even when the button doesn't have focus. 然后,当您使用Enter键时,即使按钮没有焦点,也会调用按钮的ActionListener。

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

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