Java Swing How to - Highlight few of the words of a text file in JEditorPane








Question

We would like to know how to highlight few of the words of a text file in JEditorPane.

Answer

import java.awt.Color;
/*  w ww.  ja v  a 2s  .co  m*/
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class Main {
  static MyHighlightPainter myHighlightPainter = new MyHighlightPainter(
      Color.red);

  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JEditorPane jep = new JEditorPane();
    jep.setText("Hello to the public");
    frame.add(jep);
    frame.pack();
    frame.setVisible(true);

    highlight(jep, "public");
  }

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

    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();
    }

  }

  public static 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 DefaultHighlighter.DefaultHighlightPainter {

  public MyHighlightPainter(Color color) {
    super(color);
  }
}