java 为什么 setBackground 到 JButton 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4990952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:58:10  来源:igfitidea点击:

Why does setBackground to JButton does not work?

javaswingjbuttonlook-and-feelsetbackground

提问by Roman

I have the following simple code:

我有以下简单的代码:

btn = new JButton();
btn.setBackground(backgroundColor)

I worked when I used:

我在使用时工作:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");

But it stopped to work after I have commented the above line. Does anybody know why it can happen and how I can set a background color to a button without the usage of an explicit Look and Feel?

但是在我评论了上述行后它停止工作。有谁知道为什么会发生这种情况以及如何在不使用显式外观的情况下为按钮设置背景颜色?

ADDED

添加

It seems to me that I need to use getBackground. But I do not know how.

在我看来,我需要使用getBackground. 但是我不知道怎么做。

回答by CoderCoder

it is necessary to set Opaque of the element to true for color to be filled

需要将元素的 Opaque 设置为 true 才能填充颜色

     btn = new JButton();
     btn.setOpaque(true);
     btn.setBackground(backgroundColor);

回答by proactif

From setBackground() javadoc:

来自 setBackground() javadoc:

It is up to the look and feel to honor this property, some may choose to ignore it.

尊重此属性取决于外观和感觉,有些人可能会选择忽略它。

Maybe your LAF just ignored it.

也许您的 LAF 只是忽略了它。

回答by JaNL

add btn.setBorderPainted(false)

添加 btn.setBorderPainted(false)

回答by Serhiy

Problem also can be with the way you are creating the button. Check if the code above:

问题也可能与您创建按钮的方式有关。检查上面的代码是否:

public class Test extends JApplet{

public void init() 
{  
    java.awt.EventQueue.invokeLater(new Runnable()
    {
        public void run() 
        {   
            setSize(200, 200);
            setLayout(null);

            JPanel p = new JPanel();
            getContentPane().add(p);
            p.setSize(getSize());
            p.setLayout(null);

            JButton b = new JButton("test");
            p.add(b);
            b.setBounds(10, 10, 100, 20);
            b.setBackground(Color.GREEN);

        }
    });
}

}

}

回答by Dora

Simply click once on the button you want to set background for, and then go to the properties window. Over there, the second option will be background. Click on its ellipsis, and you can change the color to your liking. The color won't be displayed on the button in your frame until after you run the program. You can see that the button is in the color you preferred.

只需在要为其设置背景的按钮上单击一次,然后转到属性窗口。在那里,第二个选项将是背景。单击它的省略号,您可以根据自己的喜好更改颜色。在您运行程序之前,颜色不会显示在您框架中的按钮上。您可以看到按钮的颜色是您喜欢的颜色。