如何设置JLabel的背景颜色?


149

在我的中JPanel,我将的背景设置JLabel为其他颜色。我可以看到单词“ Test”,它是蓝色的,但是背景完全没有变化。如何显示?

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

Answers:


311

label.setOpaque(true);

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

JavaDocs

如果为true,则组件将绘制其边界内的每个像素。否则,该组件可能不会绘制其部分或全部像素,从而使基础像素得以显示。

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



13

您必须将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中的区分大小写。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.