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; 

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!

Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

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 :


Then implement a DocumentListener interface:

public void insertUpdate(DocumentEvent e) {

public void removeUpdate(DocumentEvent e) {

public void changedUpdate(DocumentEvent e) {
correct suggestion

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!

This question has already been answered. Start a new discussion instead.