Search code examples
javauser-interfacejbuttonactionlistener

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;
    }
}

}

This class records the first two JButtons the user has clicked. firstButton represents the first button the user has clicked and secondButton represents the second button the user has clicked.

I want that when the user clicks the first JButton its colour should change to red UNTIL the second JButton has been clicked. Once the second JButton has been clicked I want the first JButton's colour to change back to the original one.

Is there anyway to do this with my current implementation?


Solution

  • To preserve your current implementation, try something like this

    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                    
                }
            }
    
    
        }
    
    }