テキストのスタイリング (太字、斜体、下線付き ...)、ファイルを開く、ファイルを保存する、検索するなどの単純な機能を使用して、NetBeans にテキスト エディターを実装しようとしています。検索機能は、ドキュメント内の指定された文字列を検索し、結果を強調表示します。これらのハイライトを削除したり、別の検索用に新しいハイライトを追加しようとすると、問題が発生します。現在、私は StyledDocument オブジェクトを jTextPane と共に使用しています。
private void textHighlight(int startAt, int endAt, Color c) {
Style sCh;
sCh = textEditor.addStyle("TextBackground", null);
StyleConstants.setBackground(sCh, c);
StyledDocument sDoc = textEditor.getStyledDocument();
sDoc.setCharacterAttributes(startAt, endAt - startAt, sCh, false);
}
private void textFind(java.awt.event.ActionEvent evt) {
int searchIndex = 0;
String searchValue = searchField.getText();
if(lastIndex != -1) {
while(searchIndex < lastIndex) {
countOccurencies++;
int i = textEditor.getText().indexOf(searchValue, searchIndex);
textHighlight(i, i+searchValue.length(), Color.MAGENTA);
searchIndex = i+searchValue.length();
}
statusLabel.setText(countOccurencies + " rezultatov.");
} else {
statusLabel.setText("Ni rezultatov!");
}
}
}
private void searchEnd(java.awt.event.ActionEvent evt) {
textEditor.removeStyle("TextBackground");
}
removeStyle() が機能していないようです。