如何设置JLabel的背景颜色?

167

在我的JPanel中,我将一个JLabel的背景颜色设置为不同的颜色。 我可以看到单词“Test”并且它是蓝色的,但是背景根本没有改变。我该如何使其显示?

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

353

使用

label.setOpaque(true);
否则背景不会被绘制,因为对于JLabel,默认的opaque值为false
根据JavaDocs:
如果为true,则组件将绘制其边界内的每个像素。否则,组件可能不会绘制其某些或所有像素,允许底层的像素透过显示。
有关更多信息,请阅读Java教程如何使用标签

42

JLabel 的背景默认是透明的。可以通过设置 opacity 为 true 来修改:

label.setOpaque(true);

15

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

6

对于背景,确保您已经将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中的大小写敏感性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接