CHAPTER 7 ■ WRITING A USER INTERFACE
Listing 7-25. The MineSweeperHelper endGame method
void endGame(boolean won) {
showAll();
String wonOrLost;
int option;
if (won) {
wonOrLost = "You won!";
} else {
wonOrLost = "You lost.";
}
option = JOptionPane.showConfirmDialog(mineSweeper.frame, wonOrLost
- " Play again?", wonOrLost,
JOptionPane.YES_NO_OPTION);
if (option == 1) {
System.exit(0);
} else {
newGame(mineSweeper.rows, mineSweeper.columns);
}
}
As we saw in the description of the showAll method, the endGame method calls the showAll method.
Then it shows the player a dialog box to indicate whether the player won or lost and ask the player
whether to play again. To show the dialog box, we use the JOptionPane class, which is one way to show a
dialog box in Swing. They probably call it JOptionPane because it has a bunch of different options. If you
examine the JavaDoc for JOptionBox, you see that it has a number of constructors, each of which creates
a different kind of dialog box. For this case, we want a box with a message, a Yes button, a No button,
and the capability to let us know which button the player clicked. To do all that, we create a String object
to hold the message (either “You won!” or “You lost.”) and define an int value to hold the return value of
the JOptionPane object. The return value indicates which button the user clicked, with 0 being “Yes” and
1 being “No.” Finally, if the user chose “No” (return value of 1), we exit the program with an exit code of
0 (which means the program shut down normally, rather than as the result of an error). If the user chose
“Yes,” we call the newGame method, which is the next method. Listing 7-26 shows the newGame method.
Listing 7-26. The MineSweeper newGame method
void newGame(int previousRows, int previousColumns) {
for (int i = 0; i < previousRows; i++) {
for (int j = 0; j < previousColumns; j++) {
mineSweeper.minePanel.remove(mineSweeper.mineButtons[i][j]);
}
}
mineSweeper.init();
mineSweeper.minePanel.validate();
mineSweeper.frame.validate();
mineSweeper.frame.pack();
updateLabels();
}
As we saw in the description of the updateButtons method, when a method needs to call a bunch of
other methods, it's best for the calling method to not do too much more than that, and the things it does
do should be simple. Otherwise, you risk having a hard method to understand and to debug. Also,