How to set the button color of a JButton (not background color)

后端 未结 5 1101
情话喂你
情话喂你 2021-01-13 04:08

I have a JButton that I would like to change the background color of to white. When using the Metal Look And Feel, I achieve the desired effect with setB

5条回答
  •  Happy的楠姐
    2021-01-13 04:46

    I use JDK 6 on XP. It looks like the Window UI doesn't follow the normal painting rules in more ways than 1. As you noticed setBackground() doesn't work. You should be able to do custom painting by telling the component not to fill in the content area:

    import java.awt.*;
    import javax.swing.*;
    
    public class ButtonBackground extends JFrame
    {
        public ButtonBackground()
        {
            setLayout( new FlowLayout() );
    
            JButton normal = new JButton("Normal");
            add(normal);
    
            JButton test1 = new JButton("Test 1")
            {
                @Override
                public void paintComponent(Graphics g)
                {
                    g.setColor( Color.GREEN );
                    g.fillRect(0, 0, getSize().width, getSize().height);
                    super.paintComponent(g);
                }
            };
            test1.setContentAreaFilled(false);
            add(test1);
        }
    
        public static void main(String[] args)
        {
            try
            {
    //          UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            }
            catch (Exception e2) {}
    
            ButtonBackground frame = new ButtonBackground();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        }
    }
    

    When you run the code as is it seems to work properly. That is when you click on the button you see the Border change. However is you run with the Windows XP LAF, the Border never changes to you don't see the button click effect.

    Therefore, I guess the issue is with the WindowUI and you would need to customize the UI which is probably too complex to do so I don't have a solution.

提交回复
热议问题