改变第一个 JButton 的颜色直到第二个被点击

Changing colour of first JButton until second one has been clicked

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.*;

public class ButtonsActionListener implements ActionListener {

    private JButton firstButton;
    private JButton secondButton;


    @Override
    public void actionPerformed(ActionEvent e) {
        if (firstClick == null) {
            firstClick = (JButton) e.getSource();
        } else {
            secondClick = (JButton) e.getSource();
            // Do something 
            firstClick = null;
            secondClick = null;
    }
}

}

这个 class 记录了用户点击的前两个 JButton。 firstButton 代表用户点击的第一个按钮,secondButton 代表用户点击的第二个按钮。

我希望当用户单击第一个 JButton 时,它的颜色应该变为红色,直到第二个 JButton 被单击。单击第二个 JButton 后,我希望第一个 JButton 的颜色变回原来的颜色。

我目前的实施是否可以做到这一点?

单击第二个按钮后,您可以将背景颜色设置为默认颜色。最初,当单击第一个按钮时,颜色会变为红色,如果单击第二个按钮,则第一个按钮的颜色会变回默认颜色。

public static void main(String[] args) {
        final JButton button = new JButton("Click me");
        final JButton button2 = new JButton("Add");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                button.setBackground(Color.RED);

            }
        });
        button2.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                button.setBackground(null);
            }
        });
    }

要确定点击了哪个按钮,并做出相应的响应,您可以这样做:

class ButtonsActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

            if (((JButton) e.getSource()) == firstButton) {
                firstButtonClicked();
            } else if (((JButton) e.getSource()) == secondButton) {
                secondButtonClicked();
           }
    }

    private void firstButtonClicked(){
        System.out.println("1st button clicked ");
        //handle second button color 
    }
    private void secondButtonClicked(){
        System.out.println("2nd button clicked ");
        //handle second button color 
    }   
}

要保留您当前的实现,请尝试这样的操作

class ButtonsActionListener implements ActionListener {

    private JButton firstButton;
    private JButton secondButton;

    @Override
    public void actionPerformed(ActionEvent e) {

    if (firstButton == null) {
            firstButton = (JButton) e.getSource();
            firstButton.setBackground(Color.RED);
        } else {
            if (firstButton == (JButton) e.getSource()) {
                firstButton.setBackground(Color.RED);
            } else {
                secondButton = (JButton) e.getSource();
                firstButton.setBackground(null);// reset to original color                    
            }
        }


    }

}