日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java documentlistener_java在DocumentListener中更改文档

發布時間:2025/3/21 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的java documentlistener_java在DocumentListener中更改文档的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。