我在使用DocumentFilter後將文本附加到JTextArea存在問題, 我需要在從文件上傳文本後在JTextArea上附加字符串,也返回從另一個JFrame的JTextArea到指定的JTextArea的字符串在使用DocumentFilter後將文本附加到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(.....)拒絕
什麼代碼是你在目前不工作的時候使用?介意發佈它? – sealz
沒問題,但它很長。必須附上兩個框架的代碼 – nnanna
也許只是您要添加「,」和「」的片段? – sealz