Why does setBackground to JButton does not work?

20.8k views Asked by At

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.

6

There are 6 answers

1
proactif On

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.

0
Serhiy On

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

        }
    });
}

}

0
Jin Lim On
    btn.setBorderPainted(false);
    btn.setOpaque(true);
    btn.setBackground(Color.BLACK);
    btn.setForeground(Color.BLUE);
0
CoderCoder On

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);
0
JaNL On

add btn.setBorderPainted(false)

0
Dora On

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.