2

I have the following problem. I create a JTextField

JTextField t = new JTextField("2");

and then add a listener.

    t.addKeyListener(new KeyAdapter()
    {

        @Override
        public void keyPressed(KeyEvent e)
        {
            System.out.println(t.getText());

        }
    });

But the getText() doesn't return the new text.

For example, if I type 5, getText() still returns 2, the old text.

akash
  • 22,664
  • 11
  • 59
  • 87
Edgar P
  • 61
  • 7
  • [This](http://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield) might help – scsere Dec 30 '15 at 13:17

1 Answers1

3

You should use keyReleased instead of keyPressed method of KeyAdapter and you will get the updated value.

Currently, keyPressed method will be fired before the text gets updated in your text field. You should get the value when user release the key.

akash
  • 22,664
  • 11
  • 59
  • 87