我使用DocumentListener来处理JTextPane文档中的任何更改。当用户输入时,我想删除JTextPane的内容,并插入一个定制的文本。在DocumentListener中更改文档是不可能的,相反,这里说了一个解决方案:java.lang.IllegalStateException while using Document Listener in TextArea, Java,但我不明白,至少我不知道在我的情况下该怎么办?
发布于 2013-02-06 19:13:58
DocumentListener实际上只适用于通知更改,不应该用来修改文本字段/文档。
相反,请使用DocumentFilter
有关示例,请查看here
仅供参考
问题的根本原因是在更新文档时会通知DocumentListener。尝试修改文档(冒着无限循环的风险)会使文档进入无效状态,因此会出现异常
使用示例更新了
这是非常基本的example...It不能处理插入或删除,但是我的测试让remove工作而不做任何事情……

public class TestHighlight {
public static void main(String[] args) {
new TestHighlight();
}
public TestHighlight() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextPane textPane = new JTextPane(new DefaultStyledDocument());
((AbstractDocument) textPane.getDocument()).setDocumentFilter(new HighlightDocumentFilter(textPane));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(textPane));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class HighlightDocumentFilter extends DocumentFilter {
private DefaultHighlightPainter highlightPainter = new DefaultHighlightPainter(Color.YELLOW);
private JTextPane textPane;
private SimpleAttributeSet background;
public HighlightDocumentFilter(JTextPane textPane) {
this.textPane = textPane;
background = new SimpleAttributeSet();
StyleConstants.setBackground(background, Color.RED);
}
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
System.out.println("insert");
super.insertString(fb, offset, text, attr);
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
System.out.println("remove");
super.remove(fb, offset, length);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String match = "test";
super.replace(fb, offset, length, text, attrs);
int startIndex = offset - match.length();
if (startIndex >= 0) {
String last = fb.getDocument().getText(startIndex, match.length()).trim();
System.out.println(last);
if (last.equalsIgnoreCase(match)) {
textPane.getHighlighter().addHighlight(startIndex, startIndex + match.length(), highlightPainter);
}
}
}
}
}发布于 2013-02-06 19:14:37
当用户键入
时,我想删除JTextPane的内容并插入自定义文本。
发布于 2013-02-06 19:33:47
包装您在SwingUtilities.invokeLater()中调用的代码
https://stackoverflow.com/questions/14727548
复制相似问题