Hello, if you want to highlight the words in a JTextComponenet in java then you can able to solve the problem with the help of code below. So, just make use of it and you will able to highlight the words in a text component.
Code:
JTextArea ta = new JTextArea();
highlight(ta, "public");
public void highlight(JTextComponent ta, String str) {
removeHighlights(ta);
try
{
Highlighter highlighter = ta.getHighlighter();
Document document = ta.getDocument();
String text = document.getText(0, document.getLength());
int pos = 0;
while ((pos = text.indexOf(str, pos)) >= 0)
{
highlighter.addHighlight(pos, pos+str.length(), myHighlightPainter);
pos += str.length();
}
}
catch (BadLocationException e)
{
}
}
public void removeHighlights(JTextComponent ta)
{
Highlighter highlighter = ta.getHighlighter();
Highlighter.Highlight[] highlighters = highlighter.getHighlights();
for (int i=0; i<highlighters.length; i++)
{
if (highlighters[i].getPainter() instanceof MyHighlightPainter)
{
highlighter.removeHighlight(highlighters[i]);
}
}
}
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter
{
public MyHighlightPainter(Color color)
{
super(color);
}
}
Bookmarks