2010-03-04 104 views
130

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

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

回答

264

使用

label.setOpaque(true); 

否则背景是不涂,因为opaque默认为falseJLabel

JavaDocs

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

欲了解更多信息,请阅读Java教程How to Use Labels

+0

1 label.setOpaque(真); – bizzr3 2014-09-07 10:56:58

38

默认情况下JLabel背景是透明的。 在那种真正的设置不透明度:

label.setOpaque(true); 
3

为背景,请确保您已导入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中的区分大小写。

11

您必须将setOpaque(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 

从的JavaDoc

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()