Search code examples
javaswingjtextfield

Replace letters with numbers as user types in a JTextField


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.


Solution

  • Use a DocumentFilter.

    Something like :

    AbstractDocument doc = (AbstractDocument)jtextField.getDocument();
    doc.setDocumentFilter(yourImplementationOfDocumentFilterWhichChangeOto0OnInsertAndReplace);