Highlighterで文字列をハイライト
Total: 19756, Today: 2, Yesterday: 5
Posted by aterai at 
Last-modified: 
Summary
Highlighterを使ってテキスト中の文字列を強調表示します。
Screenshot

Advertisement
Source Code Examples
jtc.getHighlighter().removeAllHighlights();
try {
  Highlighter highlighter = jtc.getHighlighter();
  Document doc = jtc.getDocument();
  String text = doc.getText(0, doc.getLength());
  Matcher matcher = Pattern.compile(pattern).matcher(text);
  int pos = 0;
  while (matcher.find(pos) && !matcher.group().isEmpty()) {
    pos = matcher.end();
    highlighter.addHighlight(matcher.start(), pos, highlightPainter);
  }
} catch (BadLocationException | PatternSyntaxException ex) {
  ex.printStackTrace();
}
View in GitHub: Java, KotlinDescription
- テキストコンポーネントから
Highlighterを取得し、Highlighter#addHighlight(...)メソッドで検索した文字列を追加 - 上記のサンプルではハイライト色を
DefaultHighlighter.DefaultHighlightPainterを使用して設定 
Reference
- Highlighter#addHighlight(...) (Java Platform SE 8)
 - Swing - Searching text in files & highlighting that text
 - JTextPaneで検索結果のハイライト表示と文字色変更を同時に行う