Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 336
Stefanos Kargas Avatar asked Jun 03 '10 13:06

Stefanos Kargas


People also ask

How do you add color to text in Java?

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

Which property can change the text color of the label?

The ForeColor property contains a numeric expression that represents the value of the text color in the control.

How do you change the color of something in Java?

Paint - Double click on any color at the bottom of the screen. - Choose "Define Custom Colors". - Select a color and/or use the arrows to achieve the desired color. are the numbers needed to create your new Java color.


2 Answers

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

like image 129
aioobe Avatar answered Oct 05 '22 23:10

aioobe


You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);  title.setForeground(Color.white); 

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

like image 30
Raven Dreamer Avatar answered Oct 05 '22 23:10

Raven Dreamer