javacodex.com
Java Examples
Java Examples
memu home questions

BorderLayout

The BorderLayout divides a container’s space into five areas: north, south, east, west, and center. When you add a component to a container with a BorderLayout, you need to specify which of the five areas you want to add the component. The BorderLayout class defines five constants to identify each of the five areas. The constants are NORTH, SOUTH, EAST, WEST, and CENTER.

In this example, a Jlabel is added to each of the five areas.

Source: (BorderLayoutExample.java)

import javax.swing.*;
import java.awt.*;
 
public class BorderLayoutExample {
  public static void main(String[] arguments) {
 
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("BorderLayout Example");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // setSize(int width, int height);
    f.setSize(400,300); 
    f.setLayout(new BorderLayout());
 
 
    JLabel northLable = new JLabel("N", JLabel.CENTER);
    northLable.setOpaque(true);
    northLable.setBackground(Color.RED);
 
    // Dimension(int width, int height)
    northLable.setPreferredSize(new Dimension(400, 30));
 
    JLabel southLable = new JLabel("S", JLabel.CENTER);
    southLable.setOpaque(true);
    southLable.setBackground(Color.ORANGE);
    southLable.setPreferredSize(new Dimension(4000, 30));
 
    JLabel eastLable = new JLabel("E", JLabel.CENTER);
    eastLable.setOpaque(true);
    eastLable.setBackground(Color.YELLOW);
    eastLable.setPreferredSize(new Dimension(30,300));
 
    JLabel westLable = new JLabel("W", JLabel.CENTER);
    westLable.setOpaque(true);
    westLable.setBackground(Color.GREEN);
    westLable.setPreferredSize(new Dimension(30,300));
 
    JLabel centerLable = new JLabel("Center", JLabel.CENTER);
    centerLable.setOpaque(true);
    centerLable.setBackground(Color.BLUE);
 
 
    f.add(northLable,BorderLayout.NORTH);
    f.add(southLable,BorderLayout.SOUTH);
    f.add(eastLable,BorderLayout.EAST);
    f.add(westLable,BorderLayout.WEST);
    f.add(centerLable,BorderLayout.CENTER);
 
    f.setVisible(true);
  }
}
 

Output:

$ java BorderLayoutExample
Output



Contact: javacodex@yahoo.com