我在使用 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(.....) 拒绝了
最佳答案
我不确定我是否真的理解你的问题。如果你想有一个过滤器,你可以在其中粘贴完整的数字或“,”和空格(结束或开始或输入)但不能粘贴任何其他文本你可以只更改你的 isNumeric 函数:
private boolean isNumeric(String text) {
text = text.trim();
if(",".equals(text)) return true;
ParsePosition position = new ParsePosition(0);
java.text.NumberFormat.getNumberInstance().parse(text, position);
return position.getIndex() == text.length();
}
关于java - 使用 DocumentFilter 后将文本附加到 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7484385/