You can set the DocumentFilter to the PlainDocument used by the JTextField. DocumentFilter methods will be called before changing the contents of the Document and may complement or ignore these changes:
PlainDocument doc = new PlainDocument(); doc.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { if (check(fb, offset, 0, text)) { fb.insertString(offset, text, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (check(fb, offset, length, text)) { fb.replace(offset, length, text, attrs); } }
in the above code, you have to fill in the check method so that it meets your requirements, eventually getting the field text and replacing / inserting the text to check the result.
source share