2011-05-06 6 views
2

나는 자바에서 사용자 정의 a find and replace을 만들고 있습니다. 텍스트 파일을 탐색하고 내용을 텍스트 영역에로드합니다. 이제 textBox를 검색해야하는 텍스트를 입력합니다.텍스트 영역에서 단어를 검색

텍스트를 검색하는 가장 좋은 방법은 무엇입니까? string.indexOf()을 사용하는 방법을 알고 있지만 강조 표시가 필요합니다. 그러니 제발 도와주세요.

답변

4

우선 텍스트를 검색하는 방법에 대한 정보는 Text and New Lines을 읽어보십시오.

다음 텍스트를 강조 표시하려면 형광펜을 사용해야합니다. 코드는 다음과 같습니다.

Highlighter.HighlightPainter painter = 
    new DefaultHighlighter.DefaultHighlightPainter(Color.cyan); 

int offset = text.indexOf(searchWord); 
int length = searchWord.length(); 

while (offset != -1) 
{ 
    try 
    { 
     textPane.getHighlighter().addHighlight(offset, offset + length, painter); 
     offset = text.indexOf(searchWord, offset+1); 
    } 
    catch(BadLocationException ble) { System.out.println(ble); } 
} 
+0

Camicker, 이전 강조 표시를 제거하는 방법 – mrN

+0

@mrN, 형광펜 API를 읽었습니까? – camickr

+0

그래, 내가 그랬어. – mrN

0

indexOf가 가장 쉬운 방법이지만 가장 빠른 방법은 아닙니다.

왜 indexOf가 효과적이지 않습니까? 당신은 경기의 색인을 얻을 것이며, 당신은 경기의 길이를 알고 있으므로 일치하는 텍스트를 강조 표시하십시오.

+0

: 내가 찾을 수 있으며 장착하는 데도

textArea.select(int i1, int i2); //where i1 is where your selection begins and i2 is where it ends. 

하는 쉬운 방법을 사용하지만 형광펜을 사용하지 않은? 보여 주실 수 있어요? – mrN

+0

http://www.exampledepot.com/egs/javax.swing.text/style_HiliteWords.html – krookedking

0

텍스트 편집기에서 동일한 문제가 발생합니다. 내가 강조하는 방법을 잘 모릅니다

textArea.setText(textArea.getText().replaceAll(String string1, String string2)); 
0
final String inputValue = JOptionPane.showInputDialog("Find What?"); 
final int l1 = jTextArea1.getText().indexOf(inputValue); 
final int l2 = inputValue.length(); 

if (l1 == -1) { 
    JOptionPane.showMessageDialog(null, "Search Value Not Found"); 
} else { 
    jTextArea1.select(l1, l2+l1); 
} 
관련 문제