2015-04-05 23 views
1

我寫了查找所有在TextPane(名爲textContent)是一樣TextField1(您搜索的單詞)所給詞詞的方法,它強調了他們黃色:如何將jTextPane中的所有高亮顯示的單詞更改爲jTextField中給出的單詞?

private void findAlleActionPerformed(java.awt.event.ActionEvent evt) {           
    int j = 0; 
    int i = 0; 
    int index = 0; 
    String search = TextField1.getText(); 

    try{ 
     if(!TextField1.getText().isEmpty()){ 
      while(i != -1){ 
        i = textContent.getText().indexOf(search, j); 
       if(i == -1) 
        break; 
       if(evt.getSource() == findAll || evt.getSource() == findAllButton){ 
        textContent.select(i, i + search.length()); 
       } 
       Color c = Color.YELLOW; 
       Style s = textContent.addStyle("TextBackground", null); 
       StyleConstants.setBackground(s, c); 
       StyledDocument d = textContent.getStyledDocument(); 
       d.setCharacterAttributes(textContent.getSelectionStart(), textContent.getSelectionEnd() - textContent.getSelectionStart(), textContent.getStyle("TextBackground"), false); 
       j = i + search.length(); 
       index++; 
      } 
      if (index > 0){ 
       textContent.grabFocus(); 
       textContent.setCaretPosition(textContent.getText().indexOf(search, 0)); 
       if(evt.getSource() == findAll || evt.getSource() == findAllButton){ 
        status.setText("Term: " + TextField1.getText() + ". Number of apperances: " + index); 
       } 
      } else { 
       textContent.grabFocus(); 
       if(evt.getSource() == findAll || evt.getSource() == findAllButton){ 
        status.setText("Term " + search + " was not found."); 
       } 
      } 
     } 
    } catch (Exception e){ 
     status.setText("Error finding requested term."); 
     System.err.print(e); 
    } 
} 

現在我我正在制定另一種方法changeAllActionperformed(),它將用TextField2中給出的單詞替換所有突出顯示的單詞。我試圖用textContent.replaceSelection(TextField2.getText());這樣做,但問題是它會將新單詞放在第一個高亮單詞的前面,甚至不會刪除它。我想要刪除所有突出顯示的單詞,並用Textfield2中的新單詞替換它們。我怎麼做?

回答

1

任何理由不能這麼簡單?

String replaced = textContent.getText().replace(search, TextField2.getText()); 
textContent.setText(replaced); 
+0

它的工作原理!非常感謝。我只是不知道replace()方法的存在:) – lol 2015-04-05 14:42:27

相關問題