如何设置 JLabel 的背景颜色? [英] How do I set a JLabel's background color?
问题描述
在我的 JPanel
中,我将 JLabel
的背景设置为不同的颜色.我可以看到测试"这个词,它是蓝色的,但背景根本没有改变.我怎样才能让它显示出来?
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);
推荐答案
使用
label.setOpaque(true);
否则不会绘制背景,因为JLabel
的opaque
的默认值为false
.
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
来自 JavaDocs:
如果为 true,组件会在其边界内绘制每个像素.否则,组件可能不会绘制其部分或全部像素,从而允许底层像素显示出来.
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
有关更多信息,请阅读 Java 教程 如何使用标签.
For more information, read the Java Tutorial How to Use Labels.
这篇关于如何设置 JLabel 的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!