• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:Highlighterで文字列をハイライト
#navi(../)
RIGHT:Posted by [[terai]] at 2005-12-05
*Highlighterで文字列をハイライト [#e299b873]
Highlighterを使ってテキスト中の文字列を強調表示します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#l4fc3b9f]
#code{{
public void setHighlight(JTextComponent jtc, String pattern) {
  removeHighlights(jtc);
  try{
    Highlighter hilite = jtc.getHighlighter();
    Document doc = jtc.getDocument();
    String text = doc.getText(0, doc.getLength());
    int pos = 0;
    while((pos = text.indexOf(pattern, pos)) >= 0) {
      hilite.addHighlight(pos, pos+pattern.length(), highlightPainter);
      pos += pattern.length();
    }
  }catch(BadLocationException e) {}
}
}}

**解説 [#aaff25e3]
テキストコンポーネントからHighlighterを取得し、Highlighter#addHighlightメソッドで検索した文字列を追加していきます。

上記のサンプルでは、ハイライト色をDefaultHighlighter.DefaultHighlightPainterを使って指定しています。

**参考リンク [#ncf1589c]
-[[Swing - Searching text in files & highlighting that text>http://forums.sun.com/thread.jspa?threadID=641649]]

**コメント [#z9e32e25]
- こんにちは。はじめまして。Keithと言います。このプログラムだと、テキスト中の複数の異なる文字に、それぞれハイライトを割り当てることが出来ないのですが、解決策はあるでしょうか。 -- [[Keith]] &new{2007-11-28 (水) 19:12:19};
-- こんばんは。Highlighter#addHighlightメソッドは、複数のハイライトを追加できるので、パターン毎に色を変えたいだけなら(効率とか、同じ文字列が含まれる場合とか、エラー処理などの面倒なことは考えない)、以下のようにパターンを配列にして繰り返すだけでもいいかもしれません。 -- [[terai]] &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) {
  removeHighlights(jtc);
  try{
    Highlighter hilite = jtc.getHighlighter();
    Document doc = jtc.getDocument();
    String text = doc.getText(0, doc.getLength());
    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]);
        pos += pattern[i].length();
      }
    }
  }catch(BadLocationException e) { e.printStackTrace(); }
}
}}
- こんな簡単にハイライトできるとは!。正規表現で実装すると開始位置と終了位置がより簡単で、しかも複雑にできるかも。 -- [[eternalharvest]] &new{2008-08-28 (木) 02:20:11};
-- ちょっと夏休みで帰省してました。正規表現 > そうですね。基本的には同じような要領で大丈夫だと思います。メモ:[[Swing - Content-Overlay in JTextPane>http://forums.sun.com/thread.jspa?threadID=707006]] -- [[terai]] &new{2008-09-01 (月) 13:47:05};
- こんにちは。Cakaiと申します。ハイライトされているテキストのカラーを設定することがありますか? -- [[Caokai]] &new{2009-10-15 (Thu) 23:12:47};
-- こんにちは。はじめまして。Highlighter.HighlightPainterで、文字色は変更できないかもしれません。以下のようにAttributeSetを使うのはどうでしょう。[[JTextPaneでキーワードのSyntaxHighlight>Swing/SimpleSyntaxHighlight]] -- [[terai]] &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) {
    int pos = 0;
    String text = textarea.getText();
    try {
      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,
                     Color fgcolor) {
    int pos = 0;
    String text = textPane.getText();
    StyledDocument doc = textPane.getStyledDocument();
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, fgcolor);
    try{
        while ((pos = text.indexOf(pattern, pos)) >= 0) {
            doc.setCharacterAttributes(pos, pattern.length(), sas, false);
            pos += pattern.length();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
  }
  private static JTextPane makeTestTextPane() {
    JTextPane textPane = new JTextPane();
    textPane.setText("JTextPane\nRed and Blue");
    addStyleTest(textPane, "Red", Color.RED);
    addStyleTest(textPane, "Blue", Color.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);
  }
}
}}

#comment