Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Swing setting colour to text in JTextArea

I have a JTextArea which has its text set to a string of information. In this string of information I have a variable which I would like coloured red, to do this I edit the string as follows:

"Result: <html><font color=red>" + negativeValue + "</font></html>"

I would expect this to give Result: ## where the number is red. However it just puts the following into the text area:

Result: <html><font color=red>##</font></html>

I'm not really sure how to get this working, so could someone offer advice as to how to do so?

like image 230
mino Avatar asked Feb 01 '12 14:02

mino


People also ask

How do you add color to text in Java?

Syntax: System. out. println(ANSI_COLORNAME + "This text is colored" + ANSI_RESET);

How do I add text to JTextArea?

Use textArea. append("text") , but I recomend JTextPane for more control like color, selection, etc.

Can you use basic editing operations when entering text in JTextField or JTextArea?

By default, JTextField and JTextArea are editable; you can type and edit in both text components. They can be changed to output-only areas by calling setEditable(false) .


2 Answers

JTextArea is not a component designed for styled text. If the text can be all one color, call setForeground(Color).

Otherwise use a styled text component such as a JEditorPane or JTextPane. For more info. on using them, see How to Use Editor Panes and Text Panes.

Also as pointed out by others, the entire String must start with <html> .

like image 76
Andrew Thompson Avatar answered Oct 04 '22 08:10

Andrew Thompson


You cannot use HTML in a JTextArea, but you can use it with a JEditorPane

like image 40
TPete Avatar answered Oct 04 '22 08:10

TPete