3

I have a JTextField for users to enter a serial number. The form of the serial number is such that it contains none of the letters I, O or S, since they look similar to 1, 0 and 5. What's the correct way to make it so that if the user types one of those letters, it enters the number instead?
e.g. The user types AaOo0 and it goes into the JTextField as Aa000
To clarify, this should happen as the user types each character, not after they've finished typing and left the text field.

1 Answer 1

4

Use a DocumentFilter.

Something like :

AbstractDocument doc = (AbstractDocument)jtextField.getDocument();
doc.setDocumentFilter(yourImplementationOfDocumentFilterWhichChangeOto0OnInsertAndReplace);
2
  • Man, that's much better than my crummy ol' listener based solution! +1 Nov 17, 2010 at 20:44
  • Interesting, I never knew about that solution. I'd only seen solutions where you create a subclass of AbstractDocument to do the filtering. Your approach is far superior (expresses the intent more clearly)
    – I82Much
    Nov 18, 2010 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.