TITLE:JTreeのノード中の文字列をハイライトする

Posted by at 2013-07-01

JTreeのノード中の文字列をハイライトする

JTreeのノードから文字列を検索して、HighlightPainterで強調表示します。

  • &jnlp;
  • &jar;
  • &zip;
HighlightWordInNode.png

サンプルコード

class HighlightTreeCellRenderer extends JTextField
                                implements TreeCellRenderer {
  Color backgroundSelectionColor = new Color(220, 240, 255);
  Highlighter.HighlightPainter highlightPainter =
    new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
  public String q;
  public HighlightTreeCellRenderer() {
    super();
    setOpaque(true);
    setBorder(BorderFactory.createEmptyBorder());
    setForeground(Color.BLACK);
    setBackground(Color.WHITE);
    setEditable(false);
  }
  public void removeHighlights() {
    Highlighter highlighter = getHighlighter();
    for(Highlighter.Highlight h: highlighter.getHighlights()) {
      highlighter.removeHighlight(h);
    }
  }
  @Override public Component getTreeCellRendererComponent(
      JTree tree, Object value, boolean isSelected, boolean expanded,
      boolean leaf, int row, boolean hasFocus) {
    String txt = value!=null ? value.toString() : "";
    removeHighlights();
    setText(txt);
    setBackground(isSelected ? backgroundSelectionColor : Color.WHITE);
    if(q!=null && !q.isEmpty() && txt.startsWith(q)) {
      try {
        getHighlighter().addHighlight(0, q.length(), highlightPainter);
      } catch(BadLocationException e) {
        e.printStackTrace();
      }
    }
    return this;
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、TreeCellRendererJLabelではなく、JTextFieldを使用しJTextField#getHighlighter()#addHighlight(...)で検索中の文字列をハイライト表示しています。

参考リンク

コメント