栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

java在DocumentListener中更改文档

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413840.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号