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

会有一股神秘感。 提交于 2019-12-24 07:46:27

问题


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?


回答1:


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



回答2:


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);



回答3:


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.



来源:https://stackoverflow.com/questions/54294318/how-do-i-set-the-color-of-a-jlabel-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!