java documentlistener_java在DocumentListener中更改文档

小编典典

DocumentListener实际上仅对更改通知有用,决不能用于修改文本字段/文档。

而是使用DocumentFilter

检查这里的例子

费耶

您问题的根源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);

}

}

}

}

}

2020-09-08

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值