-
category: swing
folder: Highlighter
title: Highlighterで文字列をハイライト
tags: [JTextComponent, Highlighter]
author: aterai
pubdate: 2005-12-05T11:02:14+09:00
description: Highlighterを使ってテキスト中の文字列を強調表示します。
image:
概要
概要
Highlighter
を使ってテキスト中の文字列を強調表示します。
Screenshot
サンプルコード
サンプルコード
jtc.getHighlighter().removeAllHighlights();
#spandel
try{
#spanend
#spanadd
try {
#spanend
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);
}
#spandel
}catch(BadLocationException e) {
#spanend
e.printStackTrace();
#spanadd
} catch (BadLocationException | PatternSyntaxException ex) {
#spanend
ex.printStackTrace();
}
View in GitHub: Java, Kotlin
解説
テキストコンポーネントからHighlighter
を取得し、Highlighter#addHighlight
メソッドで検索した文字列を追加していきます。
解説
- テキストコンポーネントから
Highlighter
を取得し、Highlighter#addHighlight(...)
メソッドで検索した文字列を追加
- 上記のサンプルではハイライト色を
DefaultHighlighter.DefaultHighlightPainter
を使用して設定
上記のサンプルでは、ハイライト色をDefaultHighlighter.DefaultHighlightPainter
を使って指定しています。
参考リンク
参考リンク
コメント