(^382) | Event-Driven Input and Output
// Create a JFrame object
outputFrame = new JFrame();
// Ask the JFrame object to return a content pane Container object
outputPane = outputFrame.getContentPane();
// Specify the action to take when the window is closed
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Specify the size of the JFrame object
outputFrame.setSize(300, 200);
// Specify a layout manager for the content pane object
outputPane.setLayout(new FlowLayout());
// Add output to the content pane
// Display name in first-last format
firstLast = FIRST + " " + LAST;
outputPane.add (new JLabel("Name in first-last format is "
- firstLast));
// Display name in last-first-middle format
lastFirst = LAST + ", "+ FIRST + ", ";
outputPane.add(new JLabel("Name in last-first-initial format is " - lastFirst + MIDDLE + "."));
// Make the JFrame object visible on the screen
outputFrame.setVisible(true);
}
}
8.2 Formatting Output
To format a program’s output means to control how it appears visually on the screen. In the
last section, we used the layout manager called FlowLayoutto arrange our output. In this sec-
tion, we introduce another layout manager, called GridLayout, and examine how to format
the output values themselves.
Using GridLayoutfor Tabular Output
We introduced FlowLayoutas the simplest of Java’s layout managers. The advantage of
FlowLayoutis that it entirely manages the placement of labels as we add them to a pane.
While this simplicity is convenient, it prevents us from controlling the appearance of out-
put on the screen. We do not have the option of telling FlowLayoutto place output values on
separate lines. If we use the GridLayoutmanager, however, we gain the ability to control the
position of a label with respect to others in the pane.
GridLayoutworks much the same as FlowLayoutin that we simply add labels to the pane,
and the layout manager places them consecutively into the available space. The difference
is that GridLayoutpartitions the pane into a fixed number of rows and columns—a rectan-
gular grid. Starting with the top row and the leftmost column,GridLayoutfills successive
columns, moving to the next row when it has filled every column on the row. Every column