Page 749 - Introduction to Programming with Java: A Problem Solving Approach
P. 749

                17.10 MathCalculatorProgram 715 <JPanel-reference>.add(<component>, <BorderLayout-region>);
Adding JPanel to a Window
After adding components to a JPanel, you’ll need to add the JPanel to a window. If your window uses a FlowLayout manager or a GridLayout manager, call the add method like this:
add(<JPanel-reference>);
If your window uses a BorderLayout manager, you’ll want to add a second argument to specify the
component’s region:
add(<JPanel-reference>, <BorderLayout-region>);
In the next section, we return to the math-calculator program. That will give us an opportunity to see how JPanel works in the context of a complete program.
17.10 MathCalculator Program
See the MathCalculator program listing in Figures 17.9a, 17.9b, and 17.9c. You should peruse the entire pro- gram on your own, but we’ll focus primarily on the panel-related code.
From the MathCalculator program’s createContents method, here’s the code that creates the top-
 left cell’s panel:
Apago PDF Enhancer
xPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
xPanel.add(xLabel);
xPanel.add(xBox);
The first statement instantiates the JPanel container. Since the JPanel constructor uses a center-aligned FlowLayout by default, you can write the first statement like this and get the same result:
xPanel = new JPanel();
But we prefer the original statement since it’s self-documenting. The second and third statements add the x: label and the input text box to the panel.
Further down in the createContents method, here’s the code that adds the panels to the window: add(xPanel);
add(xSqrtPanel);
add(new JLabel()); // dummy component
add(xLogPanel);
The first, second, and fourth statements add the three panels to the window’s top-left, top-right, and bottom- right cells, respectively. The third statement adds a dummy component (a blank label) to the bottom-left cell. The dummy component is necessary because without it, the xLogPanel would go into the bottom-left cell, and that’s not what you want.
There’s one additional item worth mentioning in this program. Note the String.format method call in Figure 17.9c’s actionPerformed method. The String.format method works the same as the printf method except that instead of printing a formatted value, it returns a formatted value. In the actionPerformed method, we call String.format to retrieve a formatted version of the calculated










































































   747   748   749   750   751