Layout Strategies in Java

A typical Java control panel might consist of a framed window containing a couple of buttons. Java's Abstract Windows Toolkit package (AWT) provides the necessary Frame and Button classes:

Frame gui = new Frame();
gui.add(new Button("ON"), "West");
gui.add(new Button("OFF"), "East");

Here's what the control panel looks like on the desktop:

Notice that the "ON" button occupies the left or western end of the frame, while the "OFF" button occupies the right or eastern end of the frame.

Java frames use the strategy pattern to determine where controls should be positioned when they are added to the frame using the add() method. In this situation the frame is the context, while strategies are called layout managers. Java provides several layout managers:

When a frame is created, it's provided with a BorderLayout layout manager. This strategy allows programmers to add controls to the Northern, Eastern, Western, Southern, and Central regions of the frame. If this isn't acceptable, a programmer can specify a different layout manager using the setLayout() method.

For example, a GridLayout strategy allows programmers to partition a frame into any number of rows partitioned into any number of columns. Here we partition our frame into a single row consisting of two columns:

Frame gui = new Frame();
gui.setLayout(new GridLayout(1, 2));
gui.add(new Button("ON"));
gui.add(new Button("OFF"));

Here's what the control panel looks like on the desktop:

A FlowLayout strategy attempts to horizontally center all of the controls in the frame, creating new rows as needed. Again, we use the setLayout() method to change the layout strategy:

Frame gui = new Frame();
gui.setLayout(new FlowLayout());
gui.add(new Button("ON"));
gui.add(new Button("OFF"));

Here's how the control panel appears on the desktop:

Naturally, Java programmers can define custom layout managers, if they wish.