Search code examples
javaswingjtextareahighlighting

Highlighter addHighlight not changing text color


I have a JTextArea in which I highlight some text using the addHighlight method of the Highlighter I get from the JTextArea. It highlights the text but it does not change the text color of the highlighted text to the selectedTextColor I have set.

Here is an example:

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;

public class SSCCE {

    private JFrame frame;
    private JTextArea textArea;

    public SSCCE() {
        frame = new JFrame();
        frame.setTitle("Huge Text");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        textArea = new JTextArea("abcd abcd abcd");
        textArea.setBackground(Color.DARK_GRAY);
        textArea.setForeground(Color.LIGHT_GRAY);
        textArea.setSelectionColor(Color.LIGHT_GRAY);
        textArea.setSelectedTextColor(Color.DARK_GRAY);
        Highlighter highLighter = textArea.getHighlighter();
        HighlightPainter highLightPainter = new DefaultHighlighter.DefaultHighlightPainter(textArea.getSelectionColor());
        try {
            highLighter.addHighlight(0, 10, highLightPainter);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        frame.add(new JScrollPane(textArea));

        frame.setSize(400, 350);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SSCCE();
            }
        });
    }

}

Solution

  • Worth reading about Using Text Components

    • If you intend to use an unstyled text component then choose text field, password field, formatted text field, or text area.

    • If you intend to use a styled text component, see How to Use Editor Panes and Text Panes

    enter image description here

    JTextArea doesn't support this functionality to style a sub set of the entire content. It applies styles but across the entire content.

    Find a sample code here change specific text color in java