I'm trying to make a textfield that limits a user input. I have this code:
private void jTextField5KeyTyped(java.awt.event.KeyEvent evt) {
//This limits the input:
if(jTextField5.getText().length()>=2) {
jTextField5.setText(jTextField5.getText().substring(0, 1));
}
}
It successfully limits the input. However, when I tried to press other characters on the keyboard, it changes the last character on the textfield. Any ideas to stop this? I know others will say that I should use Document(Can't remember) in making this kind of stuff, but I can't. I don't know how to do it in netbeans. Please help.
Here's a simple way to do it:
private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {
if(textField.getText().length()>=2) {
evt.consume();
}
}