Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Modified text in JTextField not returning  RSS feed

 
Jerry Crothers
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing some code to get the text when modified by the user, using a key listener. Problem is when the user changes the text in the JTextField the old text is being returned:

emailField.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
emailKeyPress(e);
}
});

public void emailKeyPress(KeyEvent e)
{
// tried e.consume() - does nothing
String emailText = this.emailField.getText().trim(); // old text..
}

Any ideas?
 
Paul Clapham
Sheriff
Posts: 22374
42
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then perhaps your listener is being notified before the contents of the component is changed. Anyway, I don't understand why people are still using KeyListeners in Swing text components when DocumentListeners are more practical and have been around for the last 6 years or so.
 
Brian Mozhdehi
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code is executed when the key is pressed, which is prior to the time when contents of the JTextField would be updated. You must wait until after the are modified to get the modified content, which can be accomplished using KeyReleased. Your code, modified as below, should work.

There is no need to use a different kind of listener, KeyListener is perfectly fine.

emailField.addKeyListener(new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
emailKeyPress(e);
}
});
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!