How do I set the colour of a label (coloured text) in Java?

Stefanos Kargas picture Stefanos Kargas · Jun 3, 2010 · Viewed 268.2k times · Source

How do I set the color of the text of a label?

myLabel.setText("Text Color: Red");
myLabel.???

Can I have two seperate colors in one label?

For example here:

The "Text Color:" to be black and the "Red" to be red.

Answer

aioobe picture aioobe · Jun 3, 2010

For single color foreground color

label.setForeground(Color.RED)

For multiple foreground colors in the same label:

(I would probably put two labels next to each other using a GridLayout or something, but here goes...)

You could use html in your label text as follows:

frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));

which produces:

enter image description here