Anon
Anon

Reputation: 25

How do I set the color of a JLabel using Java?

I will be creating multiple Jlabel components upon a JButton click. I know how to create a label and set text inside but I want this label to have a color.

I only know how to change the color of a label if it has a name but an important part of my program is when I declare the labels, I don't have names for them as shown in the code below:

newPanel.add(new JLabel("jlabel text"), g);

How can I set the color of the label?

Upvotes: 1

Views: 859

Answers (3)

Code-Apprentice
Code-Apprentice

Reputation: 83527

You should assign the label to a variable so that you can perform additional operations on it:

JLabel myLabel = new JLabel("jlabel text");
myLabel.setForeground(new java.awt.Color.RED);
newPanel.add(myLabel);

Now place this code in a function, such as an event handler for your button. Each time you click the button it creates a new JLabel. The name myLabel only refers to the current one that is being created. So yes, you can reuse the same name to refer to a different JLabel object. At a given moment, the name can only refer to one JLabel at a time.

Upvotes: 2

nullPointer
nullPointer

Reputation: 4574

yourLabel.setForeground(new java.awt.Color(r,g,b);

Upvotes: 1

camickr
camickr

Reputation: 324108

I don't have names for them as shown in the code below:

newPanel.add(new JLabel("jlabel text"), g);

So give the label a name:

JLabel label = new JLabel("label text");
label.setOpaque( true );
label.setBackground( Color.RED );
newPanel.add(label, g);

Upvotes: 3

Related Questions