Google Tag Manager

2013/07/29

JTable highlighting and filtering with regular expression

Code

class HighlightTableCellRenderer extends JTextField implements TableCellRenderer {
  private static final Color backgroundSelectionColor = new Color(220, 240, 255);
  private static final Highlighter.HighlightPainter highlightPainter
    = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
  private String pattern = "";
  private String prev = null;

  public boolean setPattern(String str) {
    if(str==null || str.equals(pattern)) {
      return false;
    }else{
      prev = pattern;
      pattern = str;
      return true;
    }
  }
  public HighlightTableCellRenderer() {
    super();
    setOpaque(true);
    setBorder(BorderFactory.createEmptyBorder());
    setForeground(Color.BLACK);
    setBackground(Color.WHITE);
    setEditable(false);
  }
  public void clearHighlights() {
    Highlighter highlighter = getHighlighter();
    for(Highlighter.Highlight h: highlighter.getHighlights()) {
      highlighter.removeHighlight(h);
    }
  }
  @Override public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column) {
    String txt = value!=null ? value.toString() : "";
    clearHighlights();
    setText(txt);
    setBackground(isSelected ? backgroundSelectionColor : Color.WHITE);
    if(pattern!=null && !pattern.isEmpty() && !pattern.equals(prev)) {
      Matcher matcher = Pattern.compile(pattern).matcher(txt);
      if(matcher.find()) {
        int start = matcher.start();
        int end   = matcher.end();
        try{
          getHighlighter().addHighlight(start, end, highlightPainter);
        }catch(BadLocationException e) {
          e.printStackTrace();
        }
      }
    }
    return this;
  }
}

References