I made a submit button but it will only be set enabled if there is text in the field. And the submit button will disable if there's no text in the field. However when I enter a, the submit button doesn't become enable and it requires me entering another character for it to do so. And I have to press the delete button again even thought I deleted all the character in the box for the button to disable.
I don't understand why this is happening, I put a print statement to see what happens as I enter characters. I noticed it prints out what I entered before the last key press.
public void keyPressed(KeyEvent e) {
System.out.println(inputField.getText()); // test input
if(inputField.getText().trim().length() == 0)
submit.setEnabled(false);
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(inputField.getText().trim().length() == 0)
JOptionPane.showMessageDialog(this, "Invalid input.", "Error", JOptionPane.ERROR_MESSAGE);
else
displayMessage();
return;
}
if(inputField.getText().trim().length() > 0) {
submit.setEnabled(true);
}
}