BorderLayout in Java Swing

BorderLayout is a layout manager in Java Swing that divides a container into five regions: North, South, East, West, and Center.

The North region is positioned at the top of the container, the South region at the bottom, the East region at the right, the West region at the left, and the Center region takes up the remaining space in the container.

To use BorderLayout in Java Swing, we can create a new instance of the BorderLayout class and set it as the layout manager for the container.

Example:

import java.awt.BorderLayout;

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

public class BorderLayoutDemo  extends JFrame {
    public BorderLayoutDemo() {
    	setTitle("BorderLayout Demo");
    	
        // Set the layout manager
        setLayout(new BorderLayout());

        // Add components to the container
        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 JLabel("Center"), BorderLayout.CENTER);

        // Set the size and make the frame visible
        setSize(300, 200);
        setVisible(true);
    }

    public static void main(String[] args) {
        new BorderLayoutDemo();
    }

}

Output:

BorderLayout in Java Swing BorderLayout Demo

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments