Java Reference
In-Depth Information
private void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane()
.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
addAndArrangePanels(frame);
addMenu(frame);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
MineSweeper mineSweeper = new MineSweeper();
mineSweeper.createAndShowGUI();
}
}
MineSweeper does the same things as the other Swing classes we've already written, and it does
quite a bit more, as you just saw. So let's step through exactly what it's doing. We'll start where you just
stopped: at the bottom, with the main method. As you learned in Chapter 1, “Writing Your First Java
Program,” the main method is the entry point for a program. Listing 7-5 shows the main method.
Listing 7-5. MineSweeper's main method
public static void main(String[] args) {
MineSweeper mineSweeper = new MineSweeper();
mineSweeper.createAndShowGUI();
}
The main method doesn't do much. It creates an instance of the MineSweeper class, which is a handy
way to avoid having to use nothing but static objects and methods throughout the class. Creating a new
object calls the constructor for that object's class. In the other classes we've seen so far, the constructors
have done nothing (and we've not coded them, relying on the default constructors for our objects). The
MineSweeper class, however, needs a true constructor. Listing 7-6 shows the constructor.
Listing 7-6. MineSweeper's constructor
public MineSweeper() {
helper = new MineSweeperHelper(this);
actionListener = new MineSweeperActionListener(this, helper);
mouseListener = new MineSweeperMouseListener(this, helper);
init();
}
The MineSweeper constructor first creates a helper object by instantiating (a fancy word for creating
an object) the MineSweeperHelper class. We have to do that first, so that we can pass the helper object to
our two listener objects. The next two lines create instances of the MineSweeperActionListener and
MineSweeperMouseListener classes. Those classes monitor the menu and the minefield (respectively) for
mouse clicks. We could have had those listeners here in the MineSweeper class (in fact, we originally had
that functionality in the MineSweeper class). Instead, we decided to have the MineSweeper class handle
just the user interface definition and push all the other tasks off to other classes. That's the kind of design
Search WWH ::




Custom Search