How do I make it possible for me to enter two letters on the keyboard and not use any other letter, number, or character in a JTextField
? For example: in a field I only want it accepted either the letter T or the letter F (upper case).
How do I make it possible for me to enter two letters on the keyboard and not use any other letter, number, or character in a JTextField
? For example: in a field I only want it accepted either the letter T or the letter F (upper case).
Events of KeyListener
only detect, but they do not prevent typing the text inside the field, and using KeyListener
to filter characters and remove them from the field is not a good practice, due to the low level that these methods work to monitor keyboard actions.
Note that if you copy and paste ( Control + C and Control anyone who has both letters or not, KeyListener
will not identify.
Ideally, use PlainDocument
or < a href="https://docs.oracle.com/javase/7/docs/api/javax/swing/text/DocumentFilter.html"> DocumentFilter
, which do not rely solely on keyboard actions such as keyPress
and directly monitor the string typed in the field.
In the duplicate example , in addition to allowing you to limit the number of characters, you are only filtering numbers, to allow only two unique letters, simply change the regex. Following the example of the given letters, it would look like this:
super.insertString(offset, str.replaceAll("([^FT])", ""), attr);
I'm allowing only the letters mentioned in their uppercase versions to be typed, not allowing any other characters, even if you try to paste them from the clipboard.
I've done an executable example that is located in in github , just compile and run.