Java AWT BorderLayout class

Introduction

The BorderLayout class implements a common layout style for top-level windows.

The BorderLayout has four narrow, fixed-width components at the four edges of a rectangle and one large area in the center.

The four sides are referred to as north, south, east, and west.

The middle area is called the center.

Here are the constructors defined by BorderLayout:

BorderLayout()  
BorderLayout(int horz, int vert) 

BorderLayout defines the following constants that specify the regions:

BorderLayout.CENTER
BorderLayout.SOUTH 
BorderLayout.EAST
BorderLayout.WEST 
BorderLayout.NORTH 

When adding components, you will use these constants with the following form of add(), which is defined by Container:

void add(Component  compRef, Object region) 

Here is an example of a BorderLayout with a component in each layout area:


import java.awt.BorderLayout;
import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.JButton;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("BorderLayout Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container container = frame.getContentPane();

        // Add a button to each of the five areas of the BorderLayout 
        container.add(new JButton("North"), BorderLayout.NORTH);
        container.add(new JButton("South"), BorderLayout.SOUTH);
        container.add(new JButton("East"), BorderLayout.EAST);
        container.add(new JButton("West"), BorderLayout.WEST);
        container.add(new JButton("Center"), BorderLayout.CENTER);

        frame.pack();/*from ww w . j  a  va2  s .  c  om*/
        frame.setVisible(true);
    }
}
import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

class Demo extends JPanel { 
  public Demo() {
    setLayout(new BorderLayout());
    add(new JButton("This is across the top."), BorderLayout.NORTH);
    add(new JLabel("The footer message might go here."), BorderLayout.SOUTH);
    add(new JButton("Right"), BorderLayout.EAST);
    add(new JButton("Left"), BorderLayout.WEST);

    add(new JTextArea("demo from demo2s.com"), BorderLayout.CENTER);
  }/*w ww . ja v  a 2s.  c  om*/
}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();

    JFrame application = new JFrame();

    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related