CHAPTER 7 ■ WRITING A USER INTERFACE
After the constructor and the init method are done setting up the game, the main method passes
control to the next method in the chain of execution: createAndShowGUI. Listing 7-8 shows the
createAndShowGUI method.
Listing 7-8. MineSweeper's createAndShowGUI method
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);
}
The createAndShowGUI method sets up and shows the JFrame object. Remember that a JFrame object
is a window. So we define the details of the program's window and then show it. Let's take it line by line
from here. The first line indicates that closing the window should also exit the program (stopping a
program and removing it from the operating system's list of running programs is often called “exiting a
program”). The second line sets the layout. In this case, it uses a BoxLayout object that places controls in
a line vertically. Notice that we have to get the content pane to be able to set the layout. Next, we pass
execution (that is, the current work being done by the program) to the addAndArrangePanels method
(which we get to next). When that's done, execution returns to this method. Then, we pass execution to
yet another method called addMenu. Notice that both of those methods take the JFrame object as
argument, which tells us that those methods do more of the work of setting up the window. In fact, they
do most of that work. Finally, we get to the last two lines, which directly affect the JFrame object. The line
that calls the pack method on the JFrame object (that is, the frame.pack(); line) tells the JVM to organize
all the controls in the JFrame object. The last line calls the setVisible method on the JFrame object,
which is Java's way of saying to make the window visible to the user. You can keep windows in memory
and make them visible or invisible. This gives better performance than re-specifying a window when you
need to hide a window.
Now let's look at the addAndArrangePanels method, which appears in listing 7-9.
Listing 7-9. MineSweeper's addAndArrangePanels method
private void addAndArrangePanels(JFrame frame) {
Border paddingBorder = BorderFactory.createEmptyBorder(5,5,5,5);
JPanel controlPanel = new JPanel();
minesFoundLabel.setBorder(paddingBorder);
minesFoundLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
minesRemainingLabel.setAlignmentX(Component.RIGHT_ALIGNMENT);
minesRemainingLabel.setBorder(paddingBorder);
minesRemainingLabel.setText("Remaining: " + mineField.getMinesRemaining());
controlPanel.add(minesFoundLabel);
controlPanel.add(minesRemainingLabel);
GridLayout gridLayout = new GridLayout(1,2);
controlPanel.setLayout(gridLayout);