Why does setBackground to JButton does not work?

雨燕双飞 提交于 2019-12-03 18:08:14

问题


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.


回答1:


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

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



回答2:


From 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.




回答3:


add btn.setBorderPainted(false)




回答4:


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

        }
    });
}

}




回答5:


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.



来源:https://stackoverflow.com/questions/4990952/why-does-setbackground-to-jbutton-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!