Sign in to follow this  

JTextField Overrides KeyListener

This topic is 1372 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

 I am trying to pass off whatever that is typed into the text field to a string whenever "enter" is pressed, however once something is typed into the JTextField, the KeyListener is automatically disabled !

 

 How can I have a text field, with a functional key listener at the same time ?

Share this post


Link to post
Share on other sites

If you only want to know when the enter key is pressed, you can use an action listener instead.

There is a good exmaple in the Oracle documentation.

 

In a nut-shell it's:

final JTextField textField = new JTextField(20);

textField.addActionListener(

  new ActionListener() {

    @Override
    public void actionPerformed(final ActionEvent evt) {

      // Enter pressed.
    }
  
  }
);

If you do need to capture other key strokes, consider using a DocumentListener.

KeyListeners can be troublesome when the registered component doesn't have focus.

Share this post


Link to post
Share on other sites


If you do need to capture other key strokes, consider using a DocumentListener.
KeyListeners can be troublesome when the registered component doesn't have focus.

 

+1  Don't use a key listener for Swing Components.  They already handle all that for you, you just have to figure out what the magical recipe is...

Share this post


Link to post
Share on other sites

This topic is 1372 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this