我想在文本中读取用户输入,然后突出显示特定单词并将其返回给用户。我能够阅读文本并将其返回给用户,但我无法弄清楚如何突出显示单个字词。如何使用java swing突出显示JTextArea中的单个单词?
答案 0 :(得分:12)
使用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));
}
}