简体   繁体   中英

Button click equivalent of pressing the enter key java

I have a button with variable name "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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