简体   繁体   中英

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. 单击“重置”按钮后不会删除文本 This is how I'm filling form

thanks in advance**

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();
    }

I agree with @camickr - any textfield will clear when executed .setText("") upon. An ActionListener should be sufficient.

clearFieldsButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        txtField.setText("");
        ...
    }
});

There is only one reason I could think of why, as you mentioned in your reply to camickr, the TextFields are not being cleared by .setText(""). You might have to refresh your JPanel using:

panel1.revalidate();
panel1.repaint();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM