在我的JPanel
中,我将一个JLabel
的背景颜色设置为不同的颜色。 我可以看到单词“Test”并且它是蓝色的,但是背景根本没有改变。我该如何使其显示?
this.setBackground(Color.white);
JLabel label = new JLabel("Test");
label.setForeground(Color.blue);
label.setBackground(Color.lightGray);
this.add(label);
JLabel 的背景默认是透明的。可以通过设置 opacity 为 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
setOpaque
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);
注意:设置为不透明会影响其可见性。请记住Java中的大小写敏感性。