I am making a text editor, And i want to make it when the user type a article then if the user select a specific word then change it's color the color will be changed and also if the user select the same word but in another place this word's color only will be changed

As indicated in this picture:

https://i.stack.imgur.com/SH0tR.png

because of all of my search results was that i change only a word's color even if it repeated it will be also colored

I am trying in JtextPane, I have searched in "Oracle Java Docs" for the JtextPane methodes but i didn't found anything

1

There are 1 best solutions below

0
Swimer On

It is necessary to use JTextPane. Just use new FindManager(yourTextPane, Color.RED);.

import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import java.awt.Color;
import java.util.ArrayList;

/**
 * @author Swimer
 */
public class FindManager {

    /**
     * Constructor
     * @param pane Swing text pane
     * @param selection The color to apply to characters similar to selection
     */
    public FindManager(JTextPane pane, Color selection) {
        Style selected = pane.getStyledDocument().addStyle("selection-text", null);
        Style defaultStyle = pane.getStyledDocument().addStyle("default", null);
        StyleConstants.setForeground(selected, selection);
        pane.addCaretListener(e -> {
            Runnable doHighlight = () -> {
                try {
                    String selectedText = pane.getSelectedText();
                    String text = pane.getStyledDocument().getText(0, pane.getStyledDocument().getLength());
                    if (selectedText != null && selectedText.length() > 0) {
                        for (Integer string : getStrings(text, selectedText, pane.getSelectionStart())) {
                            pane.getStyledDocument().setCharacterAttributes(string, selectedText.length(), selected, true);
                        }
                    }else{
                        pane.getStyledDocument().setCharacterAttributes(0, text.length(), defaultStyle, true);
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            };
            SwingUtilities.invokeLater(doHighlight);
        });
    }

    /**
     * Get positions of similar words
     * @param text The string to look for
     * @param toFind What to look for
     * @param ignore What to ignore
     * @return List of similar word positions
     */
    public static ArrayList<Integer> getStrings(String text, String toFind, int ignore){
        ArrayList<Integer> out = new ArrayList<>();
        int index = text.indexOf(toFind);
        while (index >= 0 && index != ignore) {
            out.add(index);
            index = text.indexOf(toFind, index+toFind.length());
        }
        return out;
    }
}