BorderLayout as Layout Manager in Java

May 27, 2020
Java
borderlayout
This tutorial is about the BorderLayout as Layout Manager in Java. A BorderLayout is a layout where it has a rectangular screen area divided into five regions – North, South, East, West, and Center position regions.


So, now let’s start this tutorial!

1. Open JCreator or NetBeans and make a java program with a file name of borderLayout.java.

2. Import the following packages:

import java.awt.*; //used to access the BorderLayout class
import javax.swing.*; //used to access the JFrame and JButton class

3. Initialize your variable in your Main, variable frame for JFrame, and 4 buttons namely btnNorthbtnSouthbtnEast, and btnWest as JButton.

	JFrame frame = new JFrame("BorderLayout as Layout Manager");
   JButton btnNorth, btnSouth, btnEast, btnWest;

   btnNorth = new JButton("North");
   btnSouth = new JButton("South");
   btnEast = new JButton("East");
   btnWest = new JButton("West");

 

4. To set your program layout to BorderLayout, we will use the setLayout method of the JFrame and put inside the BorderLayout class on it.

frame.getContentPane().setLayout(new BorderLayout());

 

Then, we will add the four buttons into the frame with different positions in a BorderLayout.

frame.getContentPane().add(btnNorth, BorderLayout.NORTH);
frame.getContentPane().add(btnSouth, BorderLayout.SOUTH);
frame.getContentPane().add(btnEast, BorderLayout.EAST);
frame.getContentPane().add(btnWest, BorderLayout.WEST);

The BorderLayout.NORTH assumes that the button is in the top position, BorderLayout.SOUTH in the bottom, BorderLayout.EAST in the left, and BorderLayout.WEST is in the right position, respectively.

5. Lastly, set the size, visibility, and the close operation of the frame. Have this code below:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);

Output:

output


Here’s the full code of this tutorial:

import java.awt.*; //used to access the BorderLayout class
import javax.swing.*; //used to access the JFrame and JButton class
 
public class borderLayout{
 
public static void main(String[] args) {
 	JFrame frame = new JFrame("BorderLayout as Layout Manager");
    JButton btnNorth, btnSouth, btnEast, btnWest;
 
    btnNorth = new JButton("North");
    btnSouth = new JButton("South");
    btnEast = new JButton("East");
    btnWest = new JButton("West");
 
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(btnNorth, BorderLayout.NORTH);
frame.getContentPane().add(btnSouth, BorderLayout.SOUTH);
frame.getContentPane().add(btnEast, BorderLayout.EAST);
frame.getContentPane().add(btnWest, BorderLayout.WEST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
 
}
}

 

Facebook Comments

Leave a Reply

Your email address will not be published.