Java Reference
In-Depth Information
A Component can be placed into a specified region of the BorderLayout by calling the
Container 's add method, with the first parameter being the object to add, and the second
parameter being the constraint, which for BorderLayout will be one of the five regions of the
BorderLayout , as represented by the following String constants:
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.CENTER
When a component is placed into one of these five regions, it will immediately expand to
fill that area, observing any constraints for that area. For instance, in Listing 8-1 a button is
added to each of the regions. Figure 8-6 shows the result.
Listing 8-1. BorderLayoutExample
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample extends JFrame {
public static void main(String[] args) {
new BorderLayoutExample().setVisible(true);
}
public BorderLayoutExample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("Center"), BorderLayout.CENTER);
pack();
}
}
Note Prior to JDK 1.5, it was necessary to get the content pane for a JFrame , and then add components
to the content pane. JDK 1.5 provides overridden add methods for JFrame that allow the code shown earlier
to make it appear that we are adding components directly to the JFrame —in fact we are not; the compo-
nents are being added to the component pane in the overridden add method.
Search WWH ::




Custom Search