加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 突出显示JEditorPane中的单词

发布时间:2020-12-15 07:37:25 所属栏目:Java 来源:网络整理
导读:我必须强调JEditorPane中所有出现的单词.为此,我使用以下代码: try{ javax.swing.text.DefaultHighlighter.DefaultHighlightPainter highlightPainter = new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);textPane.getHighl
我必须强调JEditorPane中所有出现的单词.为此,我使用以下代码:

try
{          
javax.swing.text.DefaultHighlighter.DefaultHighlightPainter highlightPainter = 
    new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
textPane.getHighlighter().addHighlight(startPos,endPos,highlightPainter);
}
catch(Exception ex)
{
}

但是我怎样才能给出一个单词索引的位置?

我正在从文件中读取内容,但它也正在读取HTML标记,这会扰乱单词索引.

解决方法

基本上,你应该能够在文档中查找所需的匹配项…

public class TestEditorPane01 {

    public static void main(String[] args) {
        new TestEditorPane01();
    }

    public TestEditorPane01() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JEditorPane editor = new JEditorPane();
                try {
                    editor.setPage(new File("Test.html").toURI().toURL());
                } catch (Exception exp) {
                    exp.printStackTrace();
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(editor));
                frame.setSize(400,400);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                Document document = editor.getDocument();
                try {
                    String find = "Method";
                    for (int index = 0; index + find.length() < document.getLength(); index++) {
                        String match = document.getText(index,find.length());
                        if (find.equals(match)) {
                            javax.swing.text.DefaultHighlighter.DefaultHighlightPainter highlightPainter =
                                    new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
                            editor.getHighlighter().addHighlight(index,index + find.length(),highlightPainter);
                        }
                    }
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }

            }
        });
    }
}

这将遍历整个文档并突出显示所有匹配项.这也是一个案例敏感的比赛;)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读