【问题标题】:How do I set a JLabel's background color?如何设置 JLabel 的背景颜色?
【发布时间】:2022-01-11 01:16:05
【问题描述】:

在我的JPanel 中,我将JLabel 的背景设置为不同的颜色。我可以看到“测试”这个词,它是蓝色的,但背景根本没有改变。我怎样才能让它显示出来?

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

【问题讨论】:

    标签: java swing jlabel


    【解决方案1】:

    使用

    label.setOpaque(true);
    

    否则背景不会被绘制,因为opaque 的默认值是false for JLabel

    来自JavaDocs

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

    有关更多信息,请阅读 Java 教程How to Use Labels

    【讨论】:

      【解决方案2】:

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

      label.setOpaque(true);
      

      【讨论】:

        【解决方案3】:

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

        设置不透明

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-07-07
            • 2010-12-11
            • 2013-05-06
            • 2016-03-16
            • 2012-09-21
            • 2018-10-19
            • 2011-06-14
            相关资源
            最近更新 更多