本文介绍了文档过滤器在Java中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在文本字段中超过10个字符na,它必须显示错误。对于我使用的文档过滤器:
In text field more than 10 characters na, it has to show an error. For that i used document filter:
JTextField field = (JTextField) txtFld;
AbstractDocument document = (AbstractDocument) field.getDocument();
document.setDocumentFilter(new DocumentSizeAndUppercaseFilter(10));
所以这是我的文档过滤器编码。我通过文档过滤器注册了文本字段。但这里什么也没发生。如何使用文档过滤器?
So this is my document filter coding. I registered the textfield through document filter. But nothing has happening here. How to use document filter?
DocumentSizeAndUppercaseFilter类,其中包含错误消息。
DocumentSizeAndUppercaseFilter class which has the error msg.
推荐答案
没有看到 DocumentSizeAndUppercaseFilter
的代码,我怀疑你没有实现(/覆盖) 方法:
Without seeing the code for DocumentSizeAndUppercaseFilter
I would suspect that you havn't implemented (/override) the DocumentFilter
's replace
method:
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
....
}
以下代码的屏幕截图:
Screenshot from the code below:
static class DocumentSizeAndUppercaseFilter extends DocumentFilter {
private final int max;
public DocumentSizeAndUppercaseFilter(int max) {
this.max = max;
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
if (fb.getDocument().getLength() + text.length() < max)
super.insertString(fb, offset, text.toUpperCase(), attr);
else
showError();
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
int documentLength = fb.getDocument().getLength();
if (documentLength - length + text.length() < max)
super.replace(fb, offset, length, text.toUpperCase(), attrs);
else
showError();
}
private void showError() {
JOptionPane.showMessageDialog(null, "Too many characters entered");
}
}
示例 main
:
Example main
:
public static void main(String[] args) {
JTextField firstName = new JTextField();
AbstractDocument d = (AbstractDocument) firstName.getDocument();
d.setDocumentFilter(new DocumentSizeAndUppercaseFilter(10));
JFrame frame = new JFrame("Test");
frame.add(firstName);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 60);
frame.setVisible(true);
}
这篇关于文档过滤器在Java中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!