Search code examples
javaswingjbuttonjcolorchooser

Changing a color chooser button's background color in Java


I have a Java button that opens a JColorChooser dialog. I would like for the color of the button to change according to the color selected in the dialog. I have tried calling the setBackgroundColor() method of the button, but in my case it has no effect (the button is on a JToolBar in Winsows 7). Also, this question suggests that changing a button's background is not platform independent.

Maybe the answer to this problem is not to use a button in the first place. So, my question is: is there a method of showing a "color picker" control in Java that reflects the picked color? Kind of like how MS Paint would show the picked color on the "fill with color" button.


Solution

  • You have several options:

    • Change the background of a related component, as shown in @mKorbel's answer.

    • Make the button opaque, as suggested by @Robin here.

    • Modify the background of a panel containing the button, as shown here.

    • Implement the Icon interface and apply an instance to (or near) your button, as shown here.