Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTextfield refresh in keypressed event

 
Jason Bargas
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! Just new here in coderanch...
I'm having problems with my code regarding the value of the string I get with the JTextfield.getText() method
my code goes this way:

(keypressedevent evt){
int id=evt.getId();
char c = evt.getKeyChar;
String s = JTextField.getText()+c;
System.out.print(s);
}
if the textfield contains for example: apple
and you type s, it will print apples.
but if you pressed backspace, it would still print apples
it wouldn't update until you press another key.
Is there a way to get the desired output here?










}
 
jandries Aldum
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This method will get the text of the textfield before the pressed key had any influence on the text field. (e.g. it will get apples before the backspace key had its effect of removing the "s")

Put your whole method in the keyTYPED action listener and not the key PRESSED.
It should work then.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

Perhaps you should use a DocumentListener, attached to the text fields' Document instead. A KeyListener is triggered before the text is modified, a DocumentListener afterwards.
 
Jason Bargas
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The DocumentListener solution seems nice but I'm not familiar with it.
Anyways, I found a solution already. Rather than implementing my method in the keypressed or keytyped event, I used the keyreleased event, so that I could get the exact text inside the textfield.
Thanks for everything guys!
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A DocumentListener is added to the Document of a text field (or text area, or any other text component). This Document is what contains the actual String contents, and is returned by calling getDocument().

The DocumentListener listens for three events: text added, text removed, and text replaced. There are three matching methods for that.
The advantage of a DocumentListener over a KeyListener is that it listens to all changes to the Document; not just by the user typing, but also any call to setText.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic