javaswingjtextfielddocumentfilter

How to remove DocumentFilter text from JTextField on button click


class MyDocumentFilter extends DocumentFilter {

@Override
public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {

    for (int n = string.length(); n > 0; n--) {//an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
        char c = string.charAt(n - 1);//get a single character of the string

        if (Character.isAlphabetic(c) || c == ' ') {//if its an alphabetic character or white space
            super.replace(fb, i, i1, String.valueOf(c), as);//allow update to take place for the given character
        } else {//it was not an alphabetic character or white space

        }

    }

}

@Override
public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
    super.remove(fb, i, i1);

}

@Override
public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
    super.insertString(fb, i, string, as);

}

}

I added this in JTextField. Now I want to clear JTextField text on button click. Text is Not removing after clicking on Reset buttonThis is how I'm filling form

thanks in advance**


Solution

  • Is because i used DocumentFilter on JTextField its not removing the text from JtextField. Text will be removed with DocumentFilter remove() method

        try {
            txtFirstName.getDocument().remove(0, txtFirstName.getText().length());
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }