Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

BorderLayout

BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical locations, represented by constants in the BorderLayout class: NORTH, SOUTH, EAST, WEST, and CENTER, optionally with some padding between. BorderLayout is the default layout for the content panes of JWindow and JFrame objects. Because each component is associated with a direction, BorderLayout can manage at most five components; it squashes or stretches those components to fit its constraints. As we’ll see in the second example, this means that you often want to have BorderLayout manage sets of components in their own panels.

When we add a component to a container with a border layout, we need to specify both the component and the position at which to add it. To do so, we use an overloaded version of the container’s add() method that takes an additional argument as a constraint. The constraint specifies the name of a position within the BorderLayout.

The following application sets a BorderLayout and adds our five buttons again, named for their locations:

    //file: Border1.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class Border1 extends JPanel {

      public Border1() {
        setLayout(new BorderLayout());
        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 );
      }

      public ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content