-1

I'm making a small game involving a grid of JButtons (MxN) and the main premise is to click on buttonA and then on buttonB, coloring buttonB and adjacent buttons of the same color as buttonB with the color of buttonA. I have made it so you are able to choose 3 possible difficulties. The colors are randomly generated. The main problem is getting the colors to change.

This is the method that I call after selecting the difficulty of the game:

 public static void gameMechanics(int m, int n) {
    final String[] pickedColour = {""};
    final String[] placedColour = {""};
    JButton[][] picked = new JButton[m][n];
    JButton[][] placed = new JButton[m][n];
    picked[m][n].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pickedColour[0] = picked[m][n].getText();
        }
    });
    placed[m][n].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            placedColour[0] = placed[m][n].getText();
        }
    });
    if (pickedColour[0] == "R" && placedColour[0] != "R") {
        placed[m][n].setBackground(Color.RED);
        placed[m][n].setText("R");
    }
    else if (pickedColour[0] == "G" && placedColour[0] != "G") {
        placed[m][n].setBackground(Color.GREEN);
        placed[m][n].setText("G");
    }
    else if (pickedColour[0] == "B" && placedColour[0] != "B") {
        placed[m][n].setBackground(Color.BLUE);
        placed[m][n].setText("B");
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Vuka
  • 7
  • 3

1 Answers1

0

I would consider using JPanels and painting them, using a MouseListener instead.

However, if you're set on using JButtons, try this:

button.setBackground(Color.GREEN);
button.setOpaque(true);

Note that this might not work if you're setting the look and feel using UIManager.

Also, you're doing a ton of extra work to map the color to the button - it could get confusing and cause errors down the road. Instead, you might try creating your own class:

class ColoredButton extends JButton {

        private static final long serialVersionUID = 3040767030924461426L;

        private Color color;

        public ColoredButton(Color c) {
            this.color = c;

            this.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    changeColor();
                }
            });
        }

        public void changeColor() {
            this.setBackground(this.color);
            this.setOpaque(true);
        }
    }

Now, you can construct a new ColoredButton:

// Now, this button will turn green when clicked
ColoredButton temp = new ColoredButton(Color.GREEN);
sleepToken
  • 1,866
  • 1
  • 14
  • 23