Jtextfield that accepts only two letters

Asked

Viewed 274 times

0

How do I make it in a JTextField, I can just type two letters of the keyboard and not use any other letter, number or character? For example: in a field I just want it accepted either the letter T or the letter F (uppercase).

  • Dude I’m asking how it’s done 'cause I don’t know how to do it

1 answer

3

Events of KeyListener only detect, but do not prevent text from being typed within the field, and use 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.

Not to mention, if you copy and paste(Control+C and Control+V) any text that has the two letters or not, the KeyListener will not identify.

The ideal is to use PlainDocument or DocumentFilter, which do not rely exclusively on keyboard actions such as keyPress and directly monitor the string typed in the field.

In the example of the duplicate, In addition to allowing you to limit the amount of characters, you are only filtering numbers, so 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 am allowing to be typed only the letters mentioned in their versions in high box, not allowing any other characters, even if try to paste from the Clipboard.

I made an executable example that is found on github, just compile and run.

  • 1

    Now yes, a real help!

  • 1

    @Pauloh.Hartmann on the site is not only helpful with responses, comments pointing out errors in responses is also about collaborating with content. It is enough that the author is willing to accept the criticism and correct the problem. If I have to answer all I comment that there may be errors here, I would have more than 10,000 responses on the site, but my goal is to help improve the content of the site, whether it is my own or not.

  • Of course, in this situation I agree with you. Maybe we have different views on collaborating.

  • My question has nothing to do with the Maskformatter sitada, if you look closely at what I wrote, it has nothing to do with it. Even the title is different

  • But I’ve already worked it out. and thank you

  • 2

    @Williamsbarriquero has to do with yes, so much so that I used the same solution there in this answer, and she does exactly what you asked. If you had read my answer correctly, you would have noticed the resemblance ;)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.