Java Swing GUI

BorderLayout – Java Swing – Example

In this tutorial, we are going to see an example of BorderLayout in Java Swing. BorderLayout is used to arrange the components into five regions: north, south, east, west, and center. Each region (area) can contain only one component. This is the default layout of the frame or window. BorderLayout provides five constants for each region:

  • public static final int NORTH
  • public static final int SOUTH
  • public static final int EAST
  • public static final int WEST
  • public static final int CENTER


 
 
BorderLayout constructors class:

BorderLayout Constructor
Description
JBorderLayout() Creates a border layout but without spaces between components.
JBorderLayout(int h, int v): Creates a border layout with the specified horizontal and vertical spaces between the components.

 

Example of BorderLayout in Java Swing
import java.awt.*;
import javax.swing.*;

public class MyBorderLayout
{
  MyBorderLayout()
  {
    JFrame frame = new JFrame();
    
    JButton btn1 = new JButton("North");
    JButton btn2 = new JButton("South");
    JButton btn3 = new JButton("West");
    JButton btn4 = new JButton("Ouest");
    JButton btn5 = new JButton("Center");
    
    frame.add(btn1, BorderLayout.NORTH);
    frame.add(btn2, BorderLayout.SOUTH);
    frame.add(btn3, BorderLayout.EAST);
    frame.add(btn4, BorderLayout.WEST);
    frame.add(btn5, BorderLayout.CENTER);
    
    frame.setSize(300,300);
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    new MyBorderLayout();
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *