Answers:
默认情况下,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
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中的区分大小写。