vendredi 11 septembre 2020

If condition for 9 Jbuttons simultaneously?

I have programmed 9 Jbuttons to return one of 8 colors randomly on mouse-click. I have added a Jlabel that returns the result - and I want the result to return a "Winner!" string if all Jbuttons are the same color.

So far I have written this code...

public void actionPerformed(ActionEvent e) { //Action listener method.

            if (!(e.getSource() instanceof JButton)) { 
                return;
            }

            String clickedbutton = e.getActionCommand();
            System.out.println(clickedbutton + " button clicked.");
            // ^^A test to see if button clicks are registered.

            JButton button = (JButton) e.getSource();

(switch case for colours...)

if (button.getBackground() == magenta) {
                result.setText("magenta");
            } else {
                result.setText("placeholder result");
            }

... but it only works for one button at a time!!

I've added this earlier in my code also:

buttons = new JButton[9];
            setLayout(new GridLayout(3, 3));
            for (int i = 0; i < buttons.length; i++) { ... 

Please let me know if I need to make something clearer, and plz help :)

Aucun commentaire:

Enregistrer un commentaire