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!

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");
}
commented: correct suggestion +8

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

and, have you reset the value of the JTextField?

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.