Hello,
I'm new to Java and GUI programming. I've just created my first simple GUI app which finds the appropriate FedEx zone based off of the zip coded entered in a text field. My question is how do I make it so the user can hit enter after entering in the zip code without having to mouseover the find button and click it.

Thanks in advance!

hai pxmur76,

as softswing said, you need to add/register KeyListner to your textfield so that only you can listen key events generated by the textfield.

this is the way you can handle the "enter" key event with in the text feild.please do as follows

steps:

  1. add Keylistner to your textfield

  2. i think you know KeyListner has the following methods & its signatures like (i am providing exact method signatures).

    public void keyPressed(java.awt.event.KeyEvent evt){}
    public void keyReleased(java.awt.event.KeyEvent evt){}
    public void keyTyped(java.awt.event.KeyEvent evt){}

based on your requirement implement your code in any one of the above 3 methods and provide empty implementation for the remaining methods you may want.

3.then by using getKeyCode() method of Event class you can handle the enter key as follows

      // w.r.t above method signatures

          if(evt.getKeyCode() == 10){
                   // here do whatever you want when the enter key is pressed in the text feild
          }else{
                  // your remaining code 
          }

i think you got my point.

let me know if you have any doubts in my clarification

Edited 3 Years Ago by radhakrishna.p: claryfying the solution clearly

because the question is to perform the action when entered while the button is selected.

That's just one way to interpret it.

Question:

My question is how do I make it so the user can hit enter after entering in the zip code without having to mouseover the find button and click it.

To me it doesn't seem to imply that the button needs to be selected, it would be pretty awkward anyway for both the end-user and the developer, compared to setting the same ActionListener for both the JTextField and the JButton.
This allows the user to either press the ENTER key from a JTextField that has input focus or just clicking the button, both executing the same action because they have a common ActionListener.

Edited 3 Years Ago by mvmalderen

Why not just define the button as the default button - then you can hit enter any time the focus is in the container, plus it gets painted with a highlighted appearance so you know it's the default?

getRootPane().setDefaultButton(findButton);

Comments
that would do the trick allright.
This article has been dead for over six months. Start a new discussion instead.