在我的JPanel
中,我将 a 的背景设置为JLabel
不同的颜色。我可以看到“测试”这个词,它是蓝色的,但背景根本没有改变。我怎样才能让它显示出来?
this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
JLabel 背景默认是透明的。像这样将不透明度设置为true:
label.setOpaque(true);
您必须将 setOpaque(true) 设置为 true 否则背景将不会被绘制到表单上。我认为从阅读中可以看出,如果未将其设置为 true,它将在表单上绘制一些或不绘制任何像素。默认情况下背景是透明的,这至少对我来说似乎很奇怪,但在编程方式中,您必须将其设置为 true,如下所示。
JLabel lb = new JLabel("Test");
lb.setBackground(Color.red);
lb.setOpaque(true); <--This line of code must be set to true or otherwise the
来自 JavaDocs
设置不透明
public void setOpaque(boolean isOpaque)
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.
The default value of this property is false for JComponent. However,
the default value for this property on most standard JComponent subclasses
(such as JButton and JTree) is look-and-feel dependent.
Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()
对于背景,请确保您已导入java.awt.Color
到您的包中。
在您的main
方法中,即public static void main(String[] args)
调用已导入的方法:
JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);
注意:设置 opaque 会影响其可见性。请记住 Java 中的区分大小写。