我创建了自己的 DocumentFormat,用分号分隔的整数列表。解析字符串等工作正常,但是当我想用我的新字符串替换整个文本时出现问题。
Invalid remove
调用时出现异常super.replace(fb, 0, out.length(), out, attrs);
。任何人都可以解释这个消息吗?
这是我的课程代码:
import java.util.ArrayList;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
public class IntsFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
// Do nothing so far
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Boolean test = false;
try {
Integer.parseInt(text);
test = true;
} catch (NumberFormatException e) {
test = text.equals(";");
}
if (!test) return;
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
ArrayList<String> data = toArray(sb.toString());
System.out.println(arrayToString(data));
String out = arrayToString(data);
try {
super.replace(fb, 0, out.length(), out, attrs);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
try {
super.remove(fb, offset, length);
} catch (Exception e) {
System.out.println(e.getMessage());
}
// TODO: uzupełnić
}
protected String arrayToString(ArrayList<String> input) {
String result = "";
for (int i=0; i<input.size(); i++) {
if (i == input.size() - 1)
result += input.get(i).equals("0") ? "" : input.get(i);
else
result += input.get(i) + "; ";
}
return result;
}
protected ArrayList<String> toArray(String input) {
input = input.replaceAll(";$", "; 0");
ArrayList<String> list = new ArrayList<String>();
for (String part : input.replaceAll("\\s", "").split(";")) {
try {
Integer.parseInt(part);
list.add(part);
} catch (NumberFormatException e) {}
}
return list;
}
}