Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 7 ■ WRITING A USER INTERFACE


if (e.getActionCommand().equals("Medium (16 x 16, 40 mines)")) {
int previousRows = mineSweeper.rows;
int previousColumns = mineSweeper.columns;
mineSweeper.rows = 16;
mineSweeper.columns = 16;
mineSweeper.numberOfMines = 40;
mineSweeperHelper.newGame(previousRows, previousColumns);
return;
}
if (e.getActionCommand().equals("Large (16 x 32, 100 mines)")) {
int previousRows = mineSweeper.rows;
int previousColumns = mineSweeper.columns;
mineSweeper.rows = 16;
mineSweeper.columns = 32;
mineSweeper.numberOfMines = 100;
mineSweeperHelper.newGame(previousRows, previousColumns);
return;
}
}
}

Similar to the MineSweeperMouseListener class, the MineSweeperActionListener has to have both a
MineSweeper object and a MineSweeperHelper object. To that end, it has a constructor that provides those
two objects. The only method in the class (remember that a constructor isn't a method, though it looks a
lot like one) is the actionPerformed method, which implements the only method defined by the
ActionListener interface.
The actionPerformed method listens for menu events and either exits the game or starts a new
game. In the case of starting a new game, it can either start a new game with the current settings (size of
the playing field and number of mines) or start a new game with new settings. For a new game with a
different size, the actionPerformed method gets the size of the current playing field, sets the size of the
new playing field (by setting values in the MineSweeper object), and then calls the newGame method in the
MineSweeperHelper object. Remember that the newGame method first removes the existing buttons that
comprise the playing field. That's why we have to get the current size of the playing field.
As with the MineSweeperMouseListener class, the MineSweeperActionListener is a simple class. Again,
though, it conforms to good design principles by having a clear purpose, and it helps simplify the
MineSweeper class (which was getting cluttered before we split it into five classes).
Now that we've made it through the whole MineSweeper program, let's see what we get when we're
done, in the form of a finished game in Figure 7-5.
Free download pdf