次のように、ある値から始まり別の値で終わるテキストをJTextPane
黄色で強調表示できますか?
"" JTextPaneハイライトテキスト ""
ありがとう。
多くの場合、「ハイライト」の意味に応じて、いくつかの可能性があります:-)
ドキュメントレベルで任意のテキスト部分のスタイル属性を変更してハイライトします。
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, Color.YELLOW);
doc.setCharacterAttributes(start, length, sas, false);
textPane レベルの Highlighter を介して強調表示します。
DefaultHighlighter.DefaultHighlightPainter highlightPainter =
new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
textPane.getHighlighter().addHighlight(startPos, endPos,
highlightPainter);
JTextArea textComp = new JTextArea();
// Highlight the occurrences of the word "public"
highlight(textComp, "public");
// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern)
{
// First remove all old highlights
removeHighlights(textComp);
try
{
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
// see I have updated now its not case sensitive
while ((pos = text.toUpperCase().indexOf(pattern.toUpperCase(), pos)) >= 0)
{
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp)
{
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i=0; i<hilites.length; i++)
{
if (hilites[i].getPainter() instanceof MyHighlightPainter)
{
hilite.removeHighlight(hilites[i]);
}
}
}
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter
{
public MyHighlightPainter(Color color)
{
super(color);
}
}
はい、 JTextPaneが継承するJTextComponentの関数setSelectionStartおよびsetSelectionEndを介して実行できます。
Javaの文字列比較メソッドを試しましたか
.equalsIgnoreCase("Search Target Text")
この方法では、文字列の大文字と小文字を区別せずに検索できるため、これが目的のチケットになる可能性があります。
これがマッキーの役に立てば幸いです
パフォーマンスに関しては、toUpperCase をオンにしたほうがよい
文字列テキスト = doc.getText(0, doc.getLength());
whileループではなく
しかし、良い例をありがとう。