Reputation: 21237
I have a program I've written for my kids to practice basic arithmetic. There is a JTextField on a JFrame where the student keys in the answer to a given math problem (like 8+8, they key in 16, Enter). This field accepts only integer values as entries by way of a DocumentFilter.
That part works just fine. What I want to do with this is to avoid having the user have to hit the enter key. Ideally, when the user keys in the first number (1), a check is done to see if 1 == 16. If not, nothing happens. When they subsequently type the 6, the text field displays the number 16. I want to run a check to verify if 16 == 16, and then handle the entry as if the user had also hit the Enter key.
txtAnswer.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
respondToAnswer(isTimed);
} else {
/* Check if the correct answer has been entered */
System.out.println(txtAnswer.getText());
//int userAnswer = Integer.parseInt(txtAnswer.getText());
//if (userAnswer == correctAnswer {
// respondToAnswer(isTimed);
//}
}
};
});
This code isn't quite working. It's as if it is one character behind. What I mean by that is when the user hits the '1' key (in my 8+8=16 example), the console output is an empty string. When they hit the '6' key, the output is '1'. If they then hit another integer key, the output is '16'. It's always one digit behind. Because of this, I cannot capture the entire contents of the text field to see if it matches the correct answer.
Anyone see what I am missing?
Thanks!
Upvotes: 3
Views: 1263
Reputation: 47617
Use a DocumentListener
for that instead of a KeyListener
. In all three events, you will have access to the actual text content.
To listen for the Enter on JTextField, us an ActionListener
Side note: you should almost never need a KeyListener
. On JTextComponent
, always rely on a DocumentListener
. For all the others, use appropriate Swing Key bindings. KeyListener
is really a low level API.
Upvotes: 5
Reputation: 21233
You should use DocumentListener
for this purpose. keyPressed
is probably fired before the text in the field is updated.
See How to Write a Document Listener for details and examples.
Upvotes: 5