CHAPTER 7 ■ WRITING A USER INTERFACE
MineSweeper class passes itself (with the this keyword) to this class (and to the other utility classes that
do work on its behalf). That's a common idiom for helper classes: The helper has to have a link back to
the object it's helping to be able to do anything.
Let's examine the next method: updateLabels. Listing 7-22 shows the updateLabels method.
Listing 7-22. The MineSweeperHelper updateLabels method
void updateLabels() {
mineSweeper.minesFoundLabel.setText("Found: " + mineSweeper.mineField.getMinesFound());
mineSweeper.minesRemainingLabel.setText("Remaining: " +
mineSweeper.mineField.getMinesRemaining());
}
It doesn't get much simpler than that. The updateLabels has the simple task of updating the labels
that show how many mines have been found and how many mines remain to be found. Remember that
those values are based on the player's guesses, not the actual values. The player could be wrong, which
would make the numbers wrong. That's part of the fun.
The updateButtons method does a bit more, including placing the numbers on the grid, which we
explore in a bit more detail after the listing. Listing 7-23 shows the updateButtons method.
Listing 7-23. The MineSweeperHelper updateButtons method
void updateButtons() {
for (int i = 0; i < mineSweeper.rows; i++) {
for (int j = 0; j < mineSweeper.columns; j++) {
if (mineSweeper.mineField.getMineCleared(i, j) == true) {
mineSweeper.mineButtons[i][j].removeMouseListener(mineSweeper.mouseListener);
mineSweeper.mineButtons[i][j].setBackground(Color.WHITE);
int count = mineSweeper.mineField.countAdjacentMines(i, j);
if (count > 0) {
mineSweeper.mineButtons[i][j].setIcon(MineIcon.getNumberIcon(count));
}
} else {
if (mineSweeper.mineField.getMineFlag(i, j) == Mine.flagState.MINE) {
mineSweeper.mineButtons[i][j].setIcon(MineIcon.getMineIcon());
} else if (mineSweeper.mineField.getMineFlag(i, j) == Mine.flagState.SUSPECT) {
mineSweeper.mineButtons[i][j].setIcon(MineIcon.getSuspectIcon());
} else {
mineSweeper.mineButtons[i][j].setIcon(null);
}
}
}
}
}
The updateButtons method runs through the whole grid, replacing any cleared buttons with either
empty spaces or numbers and setting the mine and suspect icons on any locations the player has
marked as either a mine or a suspect. As you can see from the listing 7-23, that takes a number of if
statements, some of them nested inside other if statements. Let's start with the first if statement (the first
line inside the for loops). If the location has been cleared, it removes the mouselistener for that location,
so that further clicks on that location won't do anything. Then it sets the background color to white and
puts the proper icon image (which might be no image at all if no mines are adjacent to the location) in