0
큰 문자열 (XML 스타일)이 있고 검색 할 단어를 캡처하기위한 텍스트 필드를 제공합니다. 발견 된 모든 단어를 강조 표시해야합니다.문자열에서 여러 단어 찾기 및 색인 가져 오기
문제는 그 단어가 해당 문자열에 여러 번 나타날 수 있지만 처음 또는 마지막 단어 만 강조 표시된다는 것입니다. 문제는 selectionStart와 ending이 항상 동일하다는 것입니다.
나를 도와 줄 수 있습니까?
public static void searchTextToFind(String textToFind) {
highlighter.removeAllHighlights();
String CurrentText = textPane.getText();
StringReader readtext;
BufferedReader readBuffer;
int i = 0;
int matches = 0;
readtext = new StringReader(CurrentText);
readBuffer = new BufferedReader(readtext);
String line;
try {
i = CurrentText.indexOf(textToFind);
int start = 0;
int end = 0;
Pattern p = Pattern.compile(textToFind);
while ((line = readBuffer.readLine()) != null) {
Matcher m = p.matcher(line);
// indicate all matches on the line
while (m.find()) {
matches++;
while (i >= 0) {
textPane.setSelectionStart(i);
textPane.setSelectionEnd(i + textToFind.length());
i = CurrentText.indexOf(textToFind, i + 1);
start = textPane.getSelectionStart();
end = textPane.getSelectionEnd();
try {
highlighter.addHighlight(start, end,
myHighlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
JOptionPane.showMessageDialog(paneXML,
matches+" matches have been found", "Matched",
JOptionPane.INFORMATION_MESSAGE);
}
'String'은 불변이고'toLowerCase()'메소드를 호출하면 새로운 문자열이 반환됩니다. 최소한, toLowerCase()를 호출 한 결과를 호출하고있는 변수에 다시 할당하십시오 (메서드 시작 근처의'textToFind'와'CurrentText'). –
나는 혼자서 문제를 풀어 몇 시간 만에 코드를 게시했습니다. – Andy
@Andy OP에 게시 한 코드가 다소 중복되었습니다. – rpg711