Java 如何突出显示 JTextArea 中的单个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20341719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to highlight a single word in a JTextArea
提问by Jonny Forney
I want to read in text the user inputs and then highlight a specific word and return it to the user. I am able to read in the text and give it back to the user, but I cant figure out how to highlight a singleword. How can I highlight a singleword in a JTextArea using java swing?
我想读取用户输入的文本,然后突出显示特定单词并将其返回给用户。我能够阅读文本并将其返回给用户,但我无法弄清楚如何突出显示单个单词。如何使用 java swing 在 JTextArea 中突出显示单个单词?
回答by Hovercraft Full Of Eels
Use the DefaultHighlighter that comes with your JTextArea. For e.g.,
使用 JTextArea 附带的 DefaultHighlighter。例如,
import java.awt.Color;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
public class Foo001 {
public static void main(String[] args) throws BadLocationException {
JTextArea textArea = new JTextArea(10, 30);
String text = "hello world. How are you?";
textArea.setText(text);
Highlighter highlighter = textArea.getHighlighter();
HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
int p0 = text.indexOf("world");
int p1 = p0 + "world".length();
highlighter.addHighlight(p0, p1, painter );
JOptionPane.showMessageDialog(null, new JScrollPane(textArea));
}
}