Sort of Pretty Panels

Layout Strategies

Recall that a Swing JPanel uses the Strategy Design Pattern to determine where subcomponents should be positioned within the panel:

Notes

·       By default a JPanel uses the flow layout strategy. This strategy attempts to center-align all of the subcomponents.

·       A grid layout allows the programmer to specify some number of rows and columns of a grid, then positions each subcomponent in the next available cell of the grid.

·       A border layout divides the panel into five regions: "North", "South", "East", "West", and "Center". The programmer can specify which region each subcomponent should be placed in. Unused regions collapse.

·       In truth, none of these strategies are very good by themselves. But notice that panels can be subcomponents of other panels. Each nested panel can have a different layout strategy. Using this idea we can create somewhat decent looking layouts.

Example: Calculator

To demonstrate these strategies, we create a simple calculator application. Here's what the final form will look like:

Design

Our design follows a simplified variant of the Model-View-Controller pattern:

Implementation

The entire application resides in two files:

Calculator.java

CalculatorPanel.java

Variation 1: Flow Layout

Flow layout heroically tries to keep the controls center-aligned, but that means moving them around each time the window is resized.

Variation 2: Border Layout

The buttons are too big and the Mul button is under the Sub button!

Variation3: Grid Layout

The buttons are still too big and the display is in the wrong place.

Variation 4: Border and Grid Layout

the display looks good, but the buttons are huge.

Variation 5: Border, Grid, and Flow Layout

My best effort. How did I do it?

Lab

Complete the implementation of initPanel5.