4

I'm having troubles setting the background color for JButtons. For example I get this when I do button.setBackground(Color.ORANGE) enter image description here

But when I disable the GTK Look and Feel it's ok. Another way to set the background? Thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Marcos
  • 4,643
  • 7
  • 33
  • 60

1 Answers1

2

GTK Look and Feel defines its own way to visually present the button, so when you use "button.setBackground(Color.ORANGE)" it only changes button underlying background and then the GTK Look and Feel draws its own (gray) representation of the button atop of the background.

In case you want a simple orange-colored button you can change button's UI for your own one, for example:

public static void main ( String[] args )
{
    JButton orangeButton = new JButton ( "X" );
    orangeButton.setUI ( new MyButtonUI ());
}

private static class MyButtonUI extends BasicButtonUI
{
    public void paint ( Graphics g, JComponent c )
    {
        JButton myButton = ( JButton ) c;
        ButtonModel buttonModel = myButton.getModel ();

        if ( buttonModel.isPressed () || buttonModel.isSelected () )
        {
            g.setColor ( Color.GRAY );
        }
        else
        {
            g.setColor ( Color.ORANGE );
        }
        g.fillRect ( 0, 0, c.getWidth (), c.getHeight () );

        super.paint ( g, c );
    }
}

This code sample will create a button that is gray on press and orange when its not pessed. Ofcourse you can style the painting as you like and change the button view.

Mikle Garin
  • 10,083
  • 37
  • 59