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
中的新单词替换它们。我怎么做?
它的工作原理!非常感谢。我只是不知道replace()方法的存在:) – lol 2015-04-05 14:42:27