我编写了一个方法,查找TextPane中的所有单词(名为textContent
),这些单词与TextField1
(您搜索的单词)中给出的单词相同,并突出显示为黄色:
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
中的新单词替换它们。我该怎么做?
答案 0 :(得分:1)
任何理由都不能这么简单吗?
String replaced = textContent.getText().replace(search, TextField2.getText());
textContent.setText(replaced);