java - 如何使用 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);
}
}
});
解决方案
不要用于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) {}
推荐阅读
- java - Process 'command 'C:/Java/jdk8/bin/java.exe'' 以非零退出值 1 结束
- javascript - npm 配置 axios
- html - 如何在 onclick 事件后停止 CSS 面板相互重叠?
- python - Python - 从未检索到任务异常 & AttributeError: __aexit__
- azure - Azcopy 将数百万个小 Blob 从存储帐户复制到您的 VM
- ios - 如何在 Xcode 中用 Swift 语言实现浏览器中例行任务的自动化?
- java - 未返回与签名 jwt 令牌中的声明相同的到期日期
- git - 另一个 GitHub 帐户错误地推送到 GitHub
- php - php finfo 将 php 文件检测为 jpeg
- windows - makefile "C:\Program" 不被识别为内部或外部命令