Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setBackground to JButton does not work?

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.

like image 888
Roman Avatar asked Feb 14 '11 10:02

Roman


People also ask

How do I trigger a JButton with a key press?

How to trigger a JButton with a key press? Add an ActionListener to the button. It will fire an event when the button is in focus and the user presses the enter key.

How do I add text to a JButton?

By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.

How will you assign the string and Icon both to the JButton?

To add icon to a button, use the Icon class, which will allow you to add an image to the button. Icon icon = new ImageIcon("E:\editicon. PNG"); JButton button7 = new JButton(icon); Above, we have set icon for button 7.


2 Answers

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);
like image 77
CoderCoder Avatar answered Sep 28 '22 20:09

CoderCoder


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.

like image 38
proactif Avatar answered Sep 28 '22 21:09

proactif