【发布时间】:2011-09-20 11:30:42
【问题描述】:
我在使用 DocumentFilter 后将文本附加到 JTextArea 时遇到问题, 从文件上传文本后,我需要在 JTextArea 上附加一个字符串,并将另一个 JFrame 的 JTextArea 中的字符串返回到指定的 JTextArea
当我没有使用 DocumentFilter.FilterBypass 直到我添加它时,一切都运行良好。它仍然有效,但仅在不添加逗号(,)或空格(“”)时才有效。这不符合我给出的规范。
我该如何解决这个问题?或者有什么算法或实现不会出现这个问题?
这是用于过滤长度的insertString代码,只允许空格和逗号
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
// if (string == null || string.trim().equals("") || string.equals(","))
// {
// return;
// }
if (isNumeric(string)) {
// if (this.length > 0 && fb.getDocument().getLength() +
// string.length()
// > this.length) {
// return;
// }
if (fb.getDocument().getLength() + string.length() > this.length || string.trim().equals("") || string.equals(",")) {
this.insertString(fb, offset, string, attr);
}
// if (string == null || string.trim().equals("") ||
// string.equals(",")) {
// return;
// }
super.insertString(fb, offset, string, attr);
}
else if (string == null || string.trim().equals("") || string.equals(",")) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (isNumeric(text)) {
if (this.length > 0 && fb.getDocument().getLength() + text.length() > this.length) {
return;
}
super.insertString(fb, offset, text, attrs);
}
}
/**
* This method tests whether given text can be represented as number. This
* method can be enhanced further for specific needs.
*
* @param text
* Input text.
* @return {@code true} if given string can be converted to number;
* otherwise returns {@code false}.
*/
private boolean isNumeric(String text) {
if (text == null || text.trim().equals("") || text.equals(",")) {
return true;
}
for (int iCount = 0; iCount < text.length(); iCount++) {
if (!Character.isDigit(text.charAt(iCount))) {
return false;
}
}
return true;
}
另外两个函数(从文件追加和从不同的帧追加)我想通过将它们的字符串值附加到使用它过滤的 JTextArea 来无辜地实现。但是被 super.insertString(.....) 拒绝
【问题讨论】:
-
您目前使用的哪些代码不起作用?介意张贴吗?
-
没问题,但它很长。必须附上两个框架的代码
-
也许只是您尝试添加“,”和“”的sn-p?
-
但是给我的规范要求我添加它们。我无法摆脱它们
-
我怎样才能绕过它。 javadoc 完全是关于这样做的