I have this code, that "disables" user input on a JTextField after n characters are inserted:
JTextField tf = new JTextField();
tf.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (((JTextField) e.getSource()).getText().length() > n) {
e.consume();
}
}
});
It works, but i was wondering if there is an alternative, because i tried it on an old slow computer and when i type something in the textfield the letter is added, then it disappear... I would like to avoid using e.consume()
after user input and directly prevent insertion instead.
Is it possible?
EDIT
I forgot to mention that i used JTextField
only for this example, but i would like this code to work with generic text input components like JTextPane
, JTextArea
, etc