1

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

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Well, what effect does pressing `Enter` have in your program? Which GUI are you using (you didn't add a tag for the GUI)? This is way too vague. Also: don't expect people here to just "fill in the code". Show your own attempts and we might tell you what's wrong. Or we might suggest a method. But writing it for you is not the purpose of this site. – RealSkeptic Dec 03 '15 at 15:36
  • If this is Swing, a JButton does not normally respond in any way to a press of the Enter key. So you don't have to do anything to get clicking on the button to do the same thing as hitting "Enter". – FredK Dec 03 '15 at 15:39
  • woops wrong one, probably this one instead http://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key – dave Dec 03 '15 at 15:39
  • When focused, pressing [Enter] and/or [Space] will have the same effect as if the user pressed the button with a mouse, that's the point of using an `ActionListener` which abstracts the mechanisms by which the button is activated – MadProgrammer Dec 03 '15 at 22:45

1 Answers1

3

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.

camickr
  • 321,443
  • 19
  • 166
  • 288