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?
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);
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.
yourLabel.setForeground(new java.awt.Color(r,g,b);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.