Lesson Sixteen

Introducing the Layout Managers


Now that we know how to add components to a frame, let's learn how to place each component where we want them. Making sure that no components are obstructing each other is the key to making Java programs attractive and user friendly. Therefore, we need to use one of the three forms of what we call layout managers. Layout managers are part of your JDK that aligns your components in various, programmer-defined regions. The first type of layout manager is the BorderLayout. The program below shows how to create a border layout:

import java.applet.*;
import java.awt.*;
public class DemoBorder extends Applet
{
private Button nb = new Button("North Button");
private Button sb = new Button("South Button");
private Button eb = new Button("East Button");
private Button wb = new Button("West Button");
private Button cb = new Button("Center Button");

public void init()
{
setLayout(new BorderLayout());
add(nb,"North");
add(sb,"South");
add(eb,"East");
add(wb,"West");
add(cb,"Center");
}
}

Seeing as none of these buttons perform any actions, there is no need for an ActionListener(). To see what we created, click here. The next type of layout is the FlowLayout. FlowLayout arranges Components in a row across the Container. If we change the setLayout() to setLayout(new FlowLayout());, we'll get this new change. You can align the buttons by typing FlowLayout.LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT within the FlowLayout() method. The last type of layout is the GridLayout. In a GridLayout, you indicate the number of rows and columns in the Container. To do this, you change the same line we changed in the FlowLayout to get setLayout(new GridLayout(2,3)); and you would get this new layout. Although these arrange things nicely, you are limited to the number of screen arangements. Using the Panel() method, you can put a GridLayout inside of a BorderLayout. You can also have nested Panels. To create a Panel, you can type Panel() if you want to use a default layout manager, or Panel(LayoutManager layout) if you want to specify a layout manager.

Question: Well, now these layouts look good, but looks can be deceiving. How do I get the buttons, text fields, and choice boxes to work?

Answer: This is where we go more in depth with using Layout Managers and the Event Model.


Lesson Fifteen | Home |

If you have a questions about any of the lessons, feel free to ask.

1