[英]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.我在 JTextField 中添加了这个。 Now I want to clear JTextField text on button click.
现在我想在单击按钮时清除 JTextField 文本。
This is how I'm filling form
这就是我填写表格的方式
thanks in advance**提前致谢**
Is because i used DocumentFilter on JTextField its not removing the text from JtextField.是因为我在 JTextField 上使用了 DocumentFilter,它没有从 JtextField 中删除文本。 Text will be removed with DocumentFilter remove() method
文本将使用 DocumentFilter remove() 方法删除
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.我同意@camickr - 在执行 .setText("") 时任何文本字段都会清除。 An ActionListener should be sufficient.
ActionListener 应该足够了。
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("").我能想到的原因只有一个,正如您在对 camickr 的回复中提到的,TextField 没有被 .setText("") 清除。 You might have to refresh your JPanel using:
您可能需要使用以下方法刷新 JPanel:
panel1.revalidate();
panel1.repaint();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.