• 追加された行はこの色です。
  • 削除された行はこの色です。
---
category: swing
folder: Highlighter
title: Highlighterで文字列をハイライト
tags: [JTextComponent, Highlighter]
author: aterai
pubdate: 2005-12-05T11:02:14+09:00
description: Highlighterを使ってテキスト中の文字列を強調表示します。
image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTN25SyRaI/AAAAAAAAAbc/i3gVEjh-mlQ/s800/Highlighter.png
---
* 概要 [#e299b873]
* 概要 [#summary]
`Highlighter`を使ってテキスト中の文字列を強調表示します。

#download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTN25SyRaI/AAAAAAAAAbc/i3gVEjh-mlQ/s800/Highlighter.png)

* サンプルコード [#l4fc3b9f]
* サンプルコード [#sourcecode]
#code(link){{
jtc.getHighlighter().removeAllHighlights();
try{
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)) {
  while (matcher.find(pos) && !matcher.group().isEmpty()) {
    pos = matcher.end();
    highlighter.addHighlight(matcher.start(), pos, highlightPainter);
  }
}catch(BadLocationException e) {
  e.printStackTrace();
} catch (BadLocationException | PatternSyntaxException ex) {
  ex.printStackTrace();
}
}}

* 解説 [#aaff25e3]
テキストコンポーネントから`Highlighter`を取得し、`Highlighter#addHighlight`メソッドで検索した文字列を追加していきます。
* 解説 [#explanation]
- テキストコンポーネントから`Highlighter`を取得し、`Highlighter#addHighlight(...)`メソッドで検索した文字列を追加
- 上記のサンプルではハイライト色を`DefaultHighlighter.DefaultHighlightPainter`を使用して設定

上記のサンプルでは、ハイライト色を`DefaultHighlighter.DefaultHighlightPainter`を使って指定しています。
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/text/Highlighter.html#addHighlight-int-int-javax.swing.text.Highlighter.HighlightPainter- Highlighter#addHighlight(...) (Java Platform SE 8)]
- [https://community.oracle.com/thread/1387954 Swing - Searching text in files & highlighting that text]
- [[JTextPaneで検索結果のハイライト表示と文字色変更を同時に行う>Swing/HighlightTextForeground]]

* 参考リンク [#ncf1589c]
- [https://forums.oracle.com/thread/1387954 Swing - Searching text in files & highlighting that text]

* コメント [#z9e32e25]
* コメント [#comment]
#comment
- こんにちは。はじめまして。Keithと言います。このプログラムだと、テキスト中の複数の異なる文字に、それぞれハイライトを割り当てることが出来ないのですが、解決策はあるでしょうか。 -- &user(Keith); &new{2007-11-28 (水) 19:12:19};
-- こんばんは。`Highlighter#addHighlight`メソッドは、複数のハイライトを追加できるので、パターン毎に色を変えたいだけなら(効率とか、同じ文字列が含まれる場合とか、エラー処理などの面倒なことは考えない)、以下のようにパターンを配列にして繰り返すだけでもいいかもしれません。 -- &user(aterai); &new{2007-11-28 (水) 20:25:31};

#code{{
private final Highlighter.HighlightPainter[] highlightPainter = {
  new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW),
  new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN)
};
private final String[] pattern = {"Swing", "win"};
public void setHighlight(JTextComponent jtc, String[] pattern) {
  try{
  try {
    Highlighter hilite = jtc.getHighlighter();
    hilite.removeAllHighlights();
    Document doc = jtc.getDocument();
    String text = doc.getText(0, doc.getLength());
    for(int i=0;i<pattern.length;i++) {
    for (int i = 0; i < pattern.length; i++) {
      int pos = 0;
      while((pos = text.indexOf(pattern[i], pos)) >= 0) {
        hilite.addHighlight(pos, pos+pattern[i].length(), highlightPainter[i]);
      while ((pos = text.indexOf(pattern[i], pos)) >= 0) {
        hilite.addHighlight(pos, pos + pattern[i].length(), highlightPainter[i]);
        pos += pattern[i].length();
      }
    }
  }catch(BadLocationException e) { e.printStackTrace(); }
  } catch (BadLocationException e) {
    e.printStackTrace();
  }
}
}}

- こんな簡単にハイライトできるとは!。正規表現で実装すると開始位置と終了位置がより簡単で、しかも複雑にできるかも。 -- &user(eternalharvest); &new{2008-08-28 (木) 02:20:11};
-- ちょっと夏休みで帰省してました。正規表現 > そうですね。基本的には同じような要領で大丈夫だと思います。メモ:[https://forums.oracle.com/thread/1382907 Swing - Content-Overlay in JTextPane]、追記: [[DefaultHighlighterの描画方法を変更する>Swing/DrawsLayeredHighlights]]に、`Matcher matcher = Pattern.compile(pattern).matcher(text);`と正規表現でハイライトするサンプルを追加。 -- &user(aterai); &new{2008-09-01 (月) 13:47:05};
-- ちょっと夏休みで帰省してました。正規表現 > そうですね。基本的には同じような要領で大丈夫だと思います。メモ: [https://community.oracle.com/thread/1382907 Swing - Content-Overlay in JTextPane]、追記: [[DefaultHighlighterの描画方法を変更する>Swing/DrawsLayeredHighlights]]に、`Matcher matcher = Pattern.compile(pattern).matcher(text);`と正規表現でハイライトするサンプルを追加。追記2: このサンプルでも正規表現を使用するように変更。 -- &user(aterai); &new{2008-09-01 (月) 13:47:05};
- こんにちは。Cakaiと申します。ハイライトされているテキストのカラーを設定することがありますか? -- &user(Caokai); &new{2009-10-15 (Thu) 23:12:47};
-- こんにちは。はじめまして。`Highlighter.HighlightPainter`で、文字色は変更できないかもしれません。以下のように`AttributeSet`を使うのはどうでしょう。[[JTextPaneでキーワードのSyntaxHighlight>Swing/SimpleSyntaxHighlight]] -- &user(aterai); &new{2009-10-16 (金) 13:04:32};
--- 用途によっては、[[JEditorPaneのHTMLEditorKitにCSSを適用>Swing/StyleSheet]]なども使えるかもしれません。

#code{{
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class HighlightTest{
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() { createAndShowGUI(); }
    });
  }
  private static void addHighlightTest(JTextComponent textarea,
                     String pattern,
                     Highlighter.HighlightPainter painter) {
    String text = textarea.getText();
    try {
      int pos = 0;
      while ((pos = text.indexOf(pattern, pos)) >= 0) {
        textarea.getHighlighter().addHighlight(
          pos, pos+pattern.length(), painter);
        pos += pattern.length();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  private static JTextArea makeTestTextArea() {
    JTextArea textArea = new JTextArea();
    textArea.setText("JTextArea\nRed and Blue");
    addHighlightTest(textArea, "Red",
      new DefaultHighlighter.DefaultHighlightPainter(Color.RED));
    addHighlightTest(textArea, "Blue",
      new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE));
    return textArea;
  }
  private static void addStyleTest(JTextPane textPane, String pattern) {
    String text = textPane.getText();
    StyledDocument doc = textPane.getStyledDocument();
    Style s = doc.getStyle(pattern.toLowerCase());
    try{
        int pos = 0;
        while ((pos = text.indexOf(pattern, pos)) >= 0) {
            doc.setCharacterAttributes(pos, pattern.length(), s, false);
            pos += pattern.length();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
  }
  private static JTextPane makeTestTextPane() {
    JTextPane textPane = new JTextPane();
    textPane.setText("JTextPane\nRed and Blue");

    StyledDocument doc = textPane.getStyledDocument();
    Style def = StyleContext.getDefaultStyleContext().getStyle(
        StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);

    Style red = doc.addStyle("red", regular);
    StyleConstants.setForeground(red, Color.RED);
    Style blue = doc.addStyle("blue", regular);
    StyleConstants.setForeground(blue, Color.BLUE);
    addStyleTest(textPane, "Red");
    addStyleTest(textPane, "Blue");
    return textPane;
  }
  public static void createAndShowGUI() {
    JPanel p = new JPanel(new GridLayout(2,1));
    p.add(new JScrollPane(makeTestTextArea()));
    p.add(new JScrollPane(makeTestTextPane()));
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(p);
    frame.setSize(320, 240);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}
}}
--- 用途によっては、[[JEditorPaneのHTMLEditorKitにCSSを適用>Swing/StyleSheet]]なども使えるかもしれません。 -- &user(aterai); &new{2009-10-16 (金) 13:05:35};
-- [[JTextPaneで検索結果のハイライト表示と文字色変更を同時に行う>Swing/HighlightTextForeground]]にサンプルコードを移動。 -- &user(aterai); &new{2014-11-10 (月) 00:05:55};
- わかりました。ほんとにありがとうございました。 -- &user(Caokai); &new{2009-10-16 (Fri) 16:42:07};

#comment