JTextField character validation
I have a program that I wrote for my children to practice basic arithmetic. The JFrame has a JTextField where the student responds in response to a given math problem (eg 8 + 8, they type 16, Enter). This field only accepts integer values as records using a DocumentFilter.
This part works great. I want to do this to prevent the user from pressing the enter key. Ideally, when the user keys are in the first number (1), a check is done to make sure 1 == 16. If not, nothing happens. When they subsequently type 6, the text box displays the number 16. I want to run a check to see if 16 == 16 is present, and then treat the entry as if the user also pressed Enter.
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 doesn't work. As if it's one character. I mean, when the user presses the "1" key (in my example 8 + 8 = 16), the console output is an empty string. When they press the "6" key, the output is "1". If you then press another integer key, the output will be "16". It is always one number behind. Because of this, I am unable to grab the entire content of the textbox to see if it matches the correct answer.
Does anyone see what I am missing?
Thank!
source to share
Use DocumentListener
for this instead KeyListener
. In all three cases, you will have access to the actual text content.
To listen Enteron a JTextField, weActionListener
Side note: you hardly need it KeyListener
. On JTextComponent
always rely on DocumentListener
. For everyone else, use the appropriate Swing key bindings. KeyListener
is really a low-level API.
source to share
For this purpose, you must use DocumentListener
. keyPressed
probably fires before the text in the field is updated.
See How to write a document listener for details .
source to share