I wrote a method that looks for all the words in TextPane (named textContent
) that are the same as the word given in TextField1
(the word you search for) and it highlights them yellow:
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);
}
}
Now I am making another method changeAllActionperformed()
that would replace ALL of the highlighted words with the word given in TextField2
. I tried doing that with textContent.replaceSelection(TextField2.getText());
but the problem is that it puts the new word just in front of the first highighted word and it doesn't even delete it. And what I would like is to delete all highlighted words and replace them all with the new word from Textfield2
. How do I do that?
Any reason it can't be this simple?
String replaced = textContent.getText().replace(search, TextField2.getText());
textContent.setText(replaced);