8.1 Frames | 379
pute the coordinates of each element within the pane and specify them in our code.
We will take the simpler approach of letting Java handle the layout automatically.
Because Java provides several different styles of automatic layout, we have to
indicate which one to use. The style of layout is determined by specifying the
name of a layout managerthrough a method associated with outputPane. This
method is called setLayout.
ThesetLayoutmethod that we apply tooutputPanetakes one argument, a lay-
out manager object. A layout manager is another of Java’s classes that we instan-
tiate with the use ofnew, just as we did to create a newJFrameobject. Let’s use the
simplest of Java’s layout managers,FlowLayout. A call tosetLayoutis written as follows:
outputPane.setLayout(new FlowLayout());
The FlowLayoutmanager’s responsibility is to automatically place elements that we add
to a content pane in the order that we add them. The first element goes in the upper-left cor-
ner of the window, and the next element goes to the right of it on the same line. When no
more room is left on a line, the manager moves to the next line in the window and contin-
ues adding elements there. One other bit of housekeeping that we need to perform relates
to the fact that the layout managers we use belong to another package, called awt. Thus, we
need to import awtalong with swing. The awtpackage is part of the javamaster package, as
you can see from the declarations below.
Let’s review the steps we have taken so far with an example code segment.
importjava.awt.; // Supplies layout manager
importjavax.swing.; // Supplies JFrame class for output display
...
JFrame outputFrame; // Declare a variable of class JFrame
Container outputPane; // Declare a container variable
outputFrame = new JFrame(); // Create a new JFrame object
// Get content pane
outputPane = outputFrame.getContentPane();
// Set the action to take on closing
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set the size of the frame
outputFrame.setSize(300, 200);
// Apply setLayout method to outputPane;
// an object of class FlowLayout is an argument
outputPane.setLayout(new FlowLayout());
Notice in this example that, as we have seen in previous chapters, we can instantiate an
object within an argument list. The argument of setLayoutis an object of the class FlowLayout.
We use newto create an instance of FlowLayoutin the argument list:
outputPane.setLayout(new FlowLayout());
Layout manager A class that
automatically manages the
placement of display elements
within a content pane on the
screen