Advertisement

JTextField Overrides KeyListener

Started by April 12, 2014 03:13 AM
1 comment, last by Glass_Knife 10 years, 9 months ago

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 ?

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

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.

Advertisement


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...

I think, therefore I am. I think? - "George Carlin"
My Website: Indie Game Programming

My Twitter: https://twitter.com/indieprogram

My Book: http://amzn.com/1305076532

This topic is closed to new replies.

Advertisement