Mourad Kourie Mourad Kourie - 5 months ago 35
Java Question

Minesweeper Object GUI

I am trying to do a simple Minesweeper game using

JFrame
, however I am having troubles with the creation of objects. I am creating 96 buttons, some of which get the property of being wrong ("F") and right ("R"):

public class GUIBase extends JFrame {

private JButton button;
private JButton fButton;


public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());

//Fields
int position;
for (int i = 0; i < 96; i++) {
position = (int) (Math.random() * 100);
if (position < 80) {
button = new JButton("R");
button.setToolTipText("Is this the correct one?");
add(button);
} else {
fButton = new JButton("F");
fButton.setToolTipText("Is this the correct one?");
add(fButton);
}
}


I then use
ActionListener
in order to check whether or not the button is correct. If the button is correct, it will get
.setEnabled(false)
, otherwise the game ends:

//Action
Action action = new Action();
button.addActionListener(action);
fButton.addActionListener(action);

}

private class Action implements ActionListener {

public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");

if (event.getSource() == button) {
button.setEnabled(false);
} else if (event.getSource() == fButton) {
JOptionPane.showMessageDialog(null, "You lost!");
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "An error ocurred");
System.exit(0);
}
}
}


Everything in the game turns out as planned, however only the last correct button ("R") and last wrong one ("F") are connected to the
ActionListener
. The rest of the buttons do not do anything when pressed.

How can I fix this?

Answer

The problem is that you only have two variables (attributes of the class GUIBase, specifically), and your are assigning to it each time you create a new button. Hence, you only have a reference to the last buttons.

You need an array of buttons. Let's see:

public class GUIBase extends JFrame {
    public final int MAX_BUTTONS = 96;
    private JButton[] buttons;
// ...
}

The next step is to create the array itself at the beginning:

public GUIBase() {
    super("Minesweeper");
    setLayout(new FlowLayout());

    this.buttons = new JButton[MAX_BUTTONS];


    //Fields
    int position;
    for (int i = 0; i < buttons.length; i++) {
        position = (int) (Math.random() * 100);

        this.buttons[ i ] = new JButton("R");
        this.buttons[ i ].setToolTipText("Is this the correct one?");
        this.add(this.buttons[ i ]);

        Action action = new Action();
        buttons[ i ].addActionListener(action);
    }
}

You'll probably need more depth in arrays in order to completely understand the code. Basically, an array is a continuous collection of variables, which you can index by its position, from 0 to n-1, being n the number of positions.

Then you'll probably be able to fill the gaps yourself.

Hope this helps.

}

Comments