我在使用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;
}
Run Code Online (Sandbox Code Playgroud)
另外两个函数(从文件追加并从不同的框架追加)我想通过将它们的字符串值附加到使用它过滤的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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
460 次 |
| 最近记录: |