首页 > 解决方案 > 如何使用 Java 荧光笔突出显示单词

问题描述

所以有一个小的 JTextArea 框架、一个 JTextField 和一个按钮。我有一些代码,其任务是从用户输入的 JTextArea 中查找单词到 JTextField 中并选择它们,但我不知道如何创建选择。谢谢你。

代码:

find2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                 String theSentence = Main.jta.getText();
                 String theWord = find.getText();
                 Highlighter h = find.getHighlighter();
                 HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY);
                 Pattern pattern = Pattern.compile(theWord, Pattern.CASE_INSENSITIVE);
                 Matcher matcher = pattern.matcher(theSentence);

                 while (matcher.find()) {
                     String extractedWord = matcher.group();    
                     System.out.println(extractedWord);
                 }

            }
                
        });

标签: javaswingtext

解决方案


不要用于getText()从文本区域获取文本。您想从 获取文本Document以确保新行字符串只是一个字符。

查看文本和换行以获得更多信息。

对于每个匹配的单词,您可以使用 的start()end()方法Matcher来获取单词的偏移量。一旦你有了偏移量,你就可以添加高光。

这是一个让您入门的基本示例:

import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextPaneHighlight extends JPanel
{
    String regx = "\\b(class|int|void|static|final|public|private|protected|float|if|else|for|while|try|catch|boolean|import|return)\\b";
    Pattern p = Pattern.compile(regx);

    JTextPane textPane = new JTextPane();

    TextPaneHighlight()
    {
        setLayout( new BorderLayout() );

        add(new JScrollPane( textPane ) );

        JButton button = new JButton("Highlight");
        add(button, BorderLayout.PAGE_END);

        button.addActionListener( (e) -> doHighlighting() );
    }

    private void doHighlighting()
    {
        SimpleAttributeSet keyword = new SimpleAttributeSet();
        StyleConstants.setForeground(keyword, Color.RED);

        try
        {
            StyledDocument doc = textPane.getStyledDocument();
            int length = doc.getLength();
            String text = doc.getText(0, length);
            Matcher m = p.matcher(text);

            while(m.find())
                doc.setCharacterAttributes(m.start(), (m.end() - m.start()), keyword, false);
        }
        catch (Exception e) { System.out.println(e); }
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("TextPaneHighlight");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TextPaneHighlight());
        frame.setSize(300, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}

只需将您的 Java 文件之一复制到文本窗格中,然后单击“突出显示”按钮。

在不使用正则表达式的情况下,您可以使用以下代码自己搜索文本:

Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );

StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
//StyleConstants.setBackground(keyWord, Color.CYAN);

try
{
    String search = textField.getText();
    int offset = 0;

    int length = textPane.getDocument().getLength();
    text = textPane.getDocument().getText(0, length);

    while ((offset = text.indexOf(search, offset)) != -1)
    {
            //textPane.getHighlighter().addHighlight(offset, offset + 5, painter); // background
            doc.setCharacterAttributes(offset, search.length(), keyWord, false); // foreground
            offset += search.length();
    }
}
catch(BadLocationException ble) {}

推荐阅读