java在DocumentListener中更改文档

我使用DocumentListener来处理JTextPane文档中的任何更改。 而用户键入我想要删除JTextPane的内容,并插入一个自定义文本。 在DocumentListener不能更改DocumentListener ,而是在这里说的是一个解决scheme: 在TextArea,Java中使用Document Listener时发生java.lang.IllegalStateException ,但是我不明白,至less我不知道该怎么做在我的情况呢?

DocumentListener实际上只适用于更改通知,绝不能用于修改文本字段/文档。

而是使用DocumentFilter

检查这里的例子

FYI

问题的根本过程是在DocumentListener被更新时通知DocumentListener 。 尝试修改文档(除了冒着无限循环的风险)将文档置于无效状态,因此是例外

更新一个例子

这是非常基本的例子…它不处理插入或删除,但我的testing已经删除了工作,没有做任何事情呢…

在这里输入图像描述

 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); } } } } } 

而用户键入我想要删除JTextPane的内容,并插入一个自定义文本。

  • 这不是DocumentListener的工作,基本上这个Listener被devise为从JTextComponent发送事件到另一个JComponent,到Swing GUI,在使用的Java中实现的方法

  • 看看DocumentFilter ,它提供了在运行时更改,修改或更新自己的Document ( JTextComponents的模型)的所需方法

将您在SwingUtilities.invokeLater()调用的代码包装起来