Highlighting Words in a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Highlighting Words in a JTextComponent

Demo Code



import java.awt.Color;

import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class Main {
  Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(
      Color.red);//from   ww w .ja v  a 2  s  .  c om

  public void main(String[] argv) {
    JTextArea textComp = new JTextArea();

    highlight(textComp, "public");
  }

  public void highlight(JTextComponent textComp, String pattern) {
    removeHighlights(textComp);

    try {
      Highlighter hilite = textComp.getHighlighter();
      Document doc = textComp.getDocument();
      String text = doc.getText(0, doc.getLength());
      int pos = 0;

      while ((pos = text.indexOf(pattern, pos)) >= 0) {
        hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
        pos += pattern.length();
      }
    } catch (BadLocationException e) {
    }
  }

  public void removeHighlights(JTextComponent textComp) {
    Highlighter hilite = textComp.getHighlighter();
    Highlighter.Highlight[] hilites = hilite.getHighlights();

    for (int i = 0; i < hilites.length; i++) {
      if (hilites[i].getPainter() instanceof MyHighlightPainter) {
        hilite.removeHighlight(hilites[i]);
      }
    }
  }
}
class MyHighlightPainter extends DefaultHighlightPainter {
  public MyHighlightPainter(Color color) {
    super(color);
  }
}

Related Tutorials