Soh*_*eil 2 java swing jtextcomponent documentlistener documentfilter
我使用a DocumentListener来处理JTextPane文档中的任何更改.而我希望删除用户类型的内容JTextPane并插入自定义文本.它是不可能改变文档的DocumentListener,而不是解决方案在这里说:
java.lang.IllegalStateException同时在TextArea,Java中使用Document Listener
,但我不明白,至少我不知道该怎么做在我的情况下?
Mad*_*mer 11
DocumentListener 实际上只适用于更改通知,不应该用于修改文本字段/文档.
相反,使用 DocumentFilter
点击这里查看示例
FYI
您的问题的根本过程DocumentListener是在文档更新时通知.尝试修改文档(除了冒无限循环的风险)将文档置于无效状态,因此异常
更新了一个示例
这是非常基本的例子......它不会处理插入或移除,但是我的测试已经删除了工作而没有做任何事情......

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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
而用户类型我想删除JTextPane的内容并改为插入自定义文本.
这不是DocumentListener的工作,基本上这个Listener旨在将事件从JTextComponent发送到另一个JComponent,到Swing GUI,在使用过的Java中实现的方法
看看DocumentFilter,这提供了在运行时更改,修改或更新自己的Document(JTextComponents模型)所需的方法