Java Reference
In-Depth Information
decision that you'll often face as you develop your programs. In this case, both my editor (Ewan) and my
technical reviewer (Massimo) suggested splitting the functionality, and they were right. (Thanks, guys.)
Even relatively simple (and yes, MineSweeper is pretty simple) software benefits from being reviewed by
others, which is something to keep in mind when you do your own programming.
You probably noticed that all the classes created by the constructor take the MineSweeper instance
itself (through the this keyword) as an argument. For now, don't concern yourself with that detail. You'll
see why that happens when we cover those classes.
Finally, the MineSweeper constructor calls the init method, which appears (again) in Listing 7-7.
Listing 7-7. MineSweeper's init method
void init() {
mineButtons = new JButton[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
JButton currentButton = new JButton();
mineButtons[i][j] = currentButton;
currentButton.setPreferredSize(buttonSize);
currentButton.setMaximumSize(buttonSize);
currentButton.setMinimumSize(buttonSize);
currentButton.addMouseListener(mouseListener);
currentButton.setEnabled(true);
currentButton.setText("");
currentButton.setIcon(null);
}
}
minePanel.setLayout(new GridLayout(rows, columns));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
minePanel.add(mineButtons[i][j]);
}
}
mineField = new MineField(rows, columns, numberOfMines);
}
The init method creates the two-dimensional array of small buttons that is the user interface to the
minefield. (The minefield itself is a more abstract object that contains the information about where the
mines are a subtle but meaningful distinction that we delve into a bit more later in the chapter.) It then
adds all those buttons to the JPanel object that holds the minefield buttons. Finally, it creates the actual
minefield. (Again, the buttons are the way we let the player access the set of information that is the
minefield.)
Note The init method gets called both when the user starts the application and when the user starts a new
game. That's why it replaces the existing instance of the MineField class with a new instance.
Search WWH ::




Custom Search