如何突出显示替换所选单词的单词?

How do I highlight the words that replaced the selected words?

此代码将所选单词替换为如下新单词:

String search = jTextField1.getText();
String replaced = jTextPane.getText().replace(search, jTextField2.getText());
jTextPane.setText(replaced);

将生词的背景设置为黄色最简单的方法是什么?

您可以使用属性:

Simple AttributeSet changed = new SimpleAttributeSet();
StyleConstants.setForeground(changed, Color.RED);
StyleConstants.setBackground(changed, Color.YELLOW);

//  Change attributes on some text

StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(20, 4, changed, false);

对于 find/replace 逻辑检查:Find/Replace, Highlight Words。您将修改突出显示代码以使用属性。

 private void changeAllActionPerformed(java.awt.event.ActionEvent evt) {
        int j = 0;
        int i = 0;
        int index = 0;
        String search = jTextField1.getText();
        String replaced = jTextPane.getText().replace(search, jTextField2.getText());
        jTextPane.setText(replaced); 
        String newtext = jTextField2.getText();

        try{
            if(!jTextField2.getText().isEmpty()){
                while(i != -1){
                        i = jTextPane.getText().indexOf(newtext, j);
                    if(i == -1)
                        break;
                    if(evt.getSource() == changeAll|| evt.getSource() == changeAllButton){
                        jTextPane.select(i, i + newtext.length());   
                    }
                    Color c = Color.YELLOW;
                    Style s = jTextPane.addStyle("TextBackground", null);
                    StyleConstants.setBackground(s, c);
                    StyledDocument d = jTextPane.getStyledDocument();
                    d.setCharacterAttributes(jTextPane.getSelectionStart(), jTextPane.getSelectionEnd() - jTextPane.getSelectionStart(), jTextPane.getStyle("TextBackground"), false);
                    j = i + search.length();
                    index++;
                }
                if (index > 0){
                    jTextPane.grabFocus();
                    jTextPane.setCaretPosition(jTextPane.getText().indexOf(newtext, 0) );
                } 
        } catch (Exception e){
            jLabel.setText("error");
            System.err.print(e);
}