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

304,013

Solution 1

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

Solution 2

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.

Solution 3

JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);

this should work

Solution 4

object.setForeground(Color.green);

*any colour you wish *object being declared earlier

Solution 5

One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)

gui_en.properties:

title.text=<html>Text color: <font color='red'>red</font></html>

gui_fr.properties:

title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>

gui_ru.properties:

title.text=<html>Цвет текста: <font color='red'>красная</font></html>
Share:
304,013
Stefanos Kargas
Author by

Stefanos Kargas

Senior Software Engineer Started as a pure desktop developer. Deeply valuing object oriented programming and organized coding according to standards and fundamentals. Currently working full-stack eager to learn new technologies and keep updated to new standards. Java, C# (.Net), Visual Basic (.Net), PHP Spring Framework, MVC, Laravel PostgreSQL, MyPHP, SQL Server, Oracle HTML, CSS, JS, Angular

Updated on July 05, 2022

Comments

  • Stefanos Kargas
    Stefanos Kargas almost 2 years

    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.

  • kleopatra
    kleopatra about 12 years
    not wrong - but nothing new as compared to the earlier answers :-)