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:
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?
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!
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.