问题

在myJPanel中,我将aJLabel的背景设置为不同的颜色。我可以看到"测试"这个词,它是蓝色的,但背景根本不会改变。我该怎么把它展示出来?

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

#1 热门回答(279 赞)

使用

label.setOpaque(true);

否则后台未绘制,因为默认值为opaqueisfalseforJLabel

来自JavaDocs

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

有关更多信息,请阅读Java TutorialHow to Use Labels


#2 热门回答(38 赞)

默认情况下,JLabel背景是透明的。将不透明度设置为true,如下所示:

label.setOpaque(true);

#3 热门回答(11 赞)

你必须将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()

原文链接