如何设置 JButton 的默认背景颜色?

How to set the default background colour of a JButton?

我无法将 JButton 的默认颜色设置为黄色?

此外,单击按钮后,它应该变为红色,如果它已经是红色,则可以单击它以变回黄色。关于我应该做什么有什么想法吗?

private void goldSeat1ActionPerformed(java.awt.event.ActionEvent evt){                                          

    // TODO add your handling code here:

    goldSeat1.setBackground(Color.YELLOW);

}                                         

private void goldSeat1MouseClicked(java.awt.event.MouseEvent evt) {                                       

    // TODO add your handling code here:

    goldSeat1.setBackground(Color.red);

}

要设置JButton 的背景色,可以使用setBackground(Color)

如果你想切换按钮,你必须给按钮添加一个ActionListener,这样当它被点击时,它就会改变。你不必必须使用MouseListener.

我在这里所做的是设置一个布尔值,每次单击按钮时它都会翻转。 (点击时 TRUE 变为 FALSE,FALSE 变为 TRUE)。 XOR 已被用于实现这一点。

由于您想要比原始 JButton 拥有更多的属性,您可以通过从 JButton.

扩展它来自定义您自己的属性

这样做可以让您享受 JComponents 的好处,同时允许您添加自己的功能。

我的自定义按钮示例:

class ToggleButton extends JButton{

    private Color onColor;
    private Color offColor;
    private boolean isOff;

    public ToggleButton(String text){
        super(text);
        init();
        updateButtonColor();
    }

    public void toggle(){
        isOff ^= true;
        updateButtonColor();            
    }

    private void init(){
        onColor = Color.YELLOW;
        offColor = Color.RED;
        isOff = true;
        setFont(new Font("Arial", Font.PLAIN, 40));     
    }

    private void updateButtonColor(){
        if(isOff){
            setBackground(offColor);
            setText("OFF");
        }           
        else{
            setBackground(onColor); 
            setText("ON");
        }           
    }   
}

包含自定义按钮的 JPanel 示例:

class DrawingSpace extends JPanel{

    private ToggleButton btn;

    public DrawingSpace(){
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(200, 200));
        btn = new ToggleButton("Toggle Button");
        setComponents();
    }

    private void setComponents(){
        add(btn);
        btn.addActionListener(new ActionListener(){             
            @Override
            public void actionPerformed(ActionEvent e){
                btn.toggle();  //change button ON/OFF status every time it is clicked
            }
        });
    }   
}

跑者class开车代码:

class ButtonToggleRunner{
    public static void main(String[] args){

        SwingUtilities.invokeLater(new Runnable(){         
            @Override
            public void run(){      
                JFrame f = new JFrame("Toggle Colors");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new DrawingSpace());
                f.pack();   
                f.setLocationRelativeTo(null);
                f.setVisible(true);             
            }
        });             
    }
}