Search code examples
javaswinghighlightjtextarea

Hightlight and change Color of Text in JTextArea


I have to write a program in which i have to highlight and change the color of the sentence in JTextarea. I have one file called original file and summary file. Original file will be displayed in textarea box and i have to highlight all the sentences of a summary file in textarea box.

I want to be highlighted and coloring text in textarea. Please can anyone tell me how can i do this? Thank you in advance :)


Solution

  • You can use JComponent#setForeground(Color) - But not on JTextArea. It's not designed for that purpose. Instead, use a JEditorPane or JTextPane.
    On these components you can also use HTML tags, like:

    "<html>My text: <font color=\"blue\">" + myString + "</font></html>"
    

    You can change the background of the JTextArea using JTextArea#setBackground (If that what you mean).