lol
lol

Reputation: 231

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

This code replaces the selected words with the new ones like this:

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

What is the easiest way to set the backgrounds of the new words to yellow?

Upvotes: 1

Views: 208

Answers (2)

confused
confused

Reputation: 121

 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);
}

Upvotes: 1

camickr
camickr

Reputation: 324207

You can use attributes:

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);

For find/replace logic check out: Find/Replace, Highlight Words. You would modify the highlighting code to use the attributes.

Upvotes: 1

Related Questions