如何设置 JLabel 的背景颜色?
在我的 JPanel
中,我将 JLabel
的背景设置为不同的颜色。我可以看到“测试”一词,它是蓝色的,但背景根本没有改变。我怎样才能让它显示出来?
this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
In my JPanel
, I set the background of a JLabel
to a different color. I can see the word "Test" and it's blue, but the background doesn't change at all. How can I get it to show?
this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
否则,不会绘制背景,因为
JLabel
的opaque
默认为false
。来自 JavaDocs :
有关详细信息,请阅读 Java 教程如何使用标签。
Use
Otherwise the background is not painted, since the default of
opaque
isfalse
forJLabel
.From the JavaDocs:
For more information, read the Java Tutorial How to Use Labels.
JLabel 背景默认是透明的。
将不透明度设置为 true,如下所示:
The JLabel background is transparent by default.
Set the opacity at true like that:
您必须将 setOpaque(true) 设置为 true,否则背景将不会绘制到表单上。我认为通过阅读,如果它没有设置为 true,它将在表单上绘制一些或不绘制任何像素。默认情况下背景是透明的,这至少对我来说似乎很奇怪,但在编程方式中,您必须将其设置为 true,如下所示。
来自 JavaDocs
setOpaque
You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.
From the JavaDocs
setOpaque
对于背景,请确保您已将
java.awt.Color
导入到您的包中。在您的
main
方法中,即public static void main(String[] args)
,调用已导入的方法:注意:设置不透明将影响其可见性。请记住 Java 中的区分大小写。
For the Background, make sure you have imported
java.awt.Color
into your package.In your
main
method, i.e.public static void main(String[] args)
, call the already imported method:NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.