我如何设置JLabel的背景颜色?

在我的JPanel ,我将JLabel的背景设置为不同的颜色。 我可以看到“testing”一词,它是蓝色的,但背景并没有改变。 我怎样才能让它显示?

 this.setBackground(Color.white); JLabel label = new JLabel("Test"); label.setForeground(Color.blue); label.setBackground(Color.lightGray); this.add(label); 

使用

 label.setOpaque(true); 

否则,不会绘制背景,因为JLabel的默认opaquefalse的。

从JavaDocs :

如果为true,则组件绘制其边界内的每个像素。 否则,该组件可能不会画出其中的一些或全部像素,从而允许底层像素显示。

有关更多信息,请阅读Java教程如何使用标签 。

JLabel背景默认是透明的。 像这样设置不透明度:

 label.setOpaque(true); 

您必须将setOpaque(true)设置为true,否则背景将不会被绘制到窗体上。 我从阅读的angular度思考,如果它不是真的,它会绘制一些或没有任何像素的forms。 背景默认是透明的,至less对我来说是很奇怪的,但是在编程方式中,您必须将其设置为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中的区分大小写。