简体   繁体   中英

Background color and GTK Look and Feel

I'm having troubles setting the background color for JButtons. For example I get this when I do button.setBackground(Color.ORANGE) 在此输入图像描述

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM