Google Tag Manager

2014/07/23

Highlight all search pattern matches in the JTextArea

Code

private Pattern getPattern() {
  String text = field.getText();
  if (text == null || text.isEmpty()) {
    return null;
  }
  try {
    String cw = checkWord.isSelected() ? "\\b" : "";
    String pattern = String.format("%s%s%s", cw, text, cw);
    int flags = checkCase.isSelected()
      ? 0
      : Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
    return Pattern.compile(pattern, flags);
  } catch (PatternSyntaxException ex) {
    field.setBackground(WARNING_COLOR);
    return null;
  }
}

private void changeHighlight() {
  field.setBackground(Color.WHITE);
  Highlighter highlighter = textArea.getHighlighter();
  highlighter.removeAllHighlights();
  Document doc = textArea.getDocument();
  try {
    Pattern pattern = getPattern();
    if (pattern != null) {
      Matcher matcher = pattern.matcher(doc.getText(0, doc.getLength()));
      int pos = 0;
      while (matcher.find(pos)) {
        int start = matcher.start();
        int end   = matcher.end();
        highlighter.addHighlight(start, end, highlightPainter);
        pos = end;
      }
    }
    JLabel label = layerUI.hint;
    Highlighter.Highlight[] array = highlighter.getHighlights();
    int hits = array.length;
    if (hits == 0) {
      current = -1;
      label.setOpaque(true);
    } else {
      current = (current + hits) % hits;
      label.setOpaque(false);
      Highlighter.Highlight hh = highlighter.getHighlights()[current];
      highlighter.removeHighlight(hh);
      highlighter.addHighlight(
          hh.getStartOffset(), hh.getEndOffset(), currentPainter);
      scrollToCenter(textArea, hh.getStartOffset());
    }
    label.setText(String.format("%02d / %02d%n", current + 1, hits));
  } catch (BadLocationException e) {
    e.printStackTrace();
  }
  field.repaint();
}

References