Skip to content
Advertisement

Restrict JTextField to only accept certain characters

I have 4 JTextFields that should only accept certain characters:

  1. binary digits (0, 1)
  2. octal digits, so (07)
  3. all digits (09)
  4. all hexadecimal characters (09, af, AF)

The user must not be able to input a forbidden character.

I know how I could validate the input afterwards, but not how to filter it.


I tried using a MaskFormatter, but then I can’t enter anything at all.

MaskFormatter binaryFormatter = new MaskFormatter();
binaryFormatter.setValidCharacters("01");
JFormattedTextField binaryText = new JFormattedTextField(binaryFormatter);

Advertisement

Answer

You don’t want to format the value, you want to filter the content. Use a DocumentFilter on a plain on JTextField

Start by having a look at Implementing a DocumntFilter and Examples for more details…

As an example, a “binary filter”, which will only accept 0 and 1

public class BinaryDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset,
            String text, AttributeSet attr)
            throws BadLocationException {
        StringBuilder buffer = new StringBuilder(text.length());
        for (int i = text.length() - 1; i >= 0; i--) {
            char ch = text.charAt(i);
            if (ch == '0' || ch == '1') {
                buffer.append(ch);
            }
        }
        super.insertString(fb, offset, buffer.toString(), attr);
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb,
            int offset, int length, String string, AttributeSet attr) throws BadLocationException {
        if (length > 0) {
            fb.remove(offset, length);
        }
        insertString(fb, offset, string, attr);
    }
}

Which can be applied directly to the field’s Document:

JTextField binaryField = new JTextField(10);
((AbstractDocument)binaryField.getDocument()).setDocumentFilter(new BinaryDocumentFilter());
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement