954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help! JTextfield refresh in keypressed event

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?
Thanks in advance!

malchus
Newbie Poster
2 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

This is not working since using a literal backspace character will not remove characters from the string. You could check: if(c == '\b') and remove the last character. You will probably have issues if text is inserted in the middle of the text. I would suggest using a DocumentListener :

jTextField.getDocument().addDocumentListener(this);

Then implement a DocumentListener interface:

@Override
public void insertUpdate(DocumentEvent e) {
    System.out.println("insert");
}

@Override
public void removeUpdate(DocumentEvent e) {
    System.out.println("remove");
}

@Override
public void changedUpdate(DocumentEvent e) {
    System.out.println("changed");
}
nmaillet
Posting Whiz in Training
236 posts since Aug 2008
Reputation Points: 69
Solved Threads: 53
 

You don't explain What does your current code print out now?

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

and, have you reset the value of the JTextField?

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

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!

malchus
Newbie Poster
2 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: