• How to use Border Layout in Java

    In our previous post, we discussed about Flow Layout. Another layout manager that commonly used is the Border Layout. Border Layout layout its component in 5 places/directions: North, East, South, West and Center.

    border layout regions

    Border Layout Java Example

    package com.javapointers.javase;
    
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class BorderLayoutTest {
    
        JButton btnNorth, btnEast, btnWest, btnSouth, btnCenter;
        JFrame frame;
    
        public BorderLayoutTest() {
            btnNorth = new JButton("North");
            btnEast = new JButton("East");
            btnWest = new JButton("West");
            btnSouth = new JButton("South");
            btnCenter = new JButton("Center");
    
            frame = new JFrame();
            frame.setSize(500, 400);
            frame.setLayout(new BorderLayout());
            frame.add(btnNorth, BorderLayout.NORTH);
            frame.add(btnEast, BorderLayout.EAST);
            frame.add(btnWest, BorderLayout.WEST);
            frame.add(btnSouth, BorderLayout.SOUTH);
            frame.add(btnCenter, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    
        public static void main(String args[]) {
            BorderLayoutTest test = new BorderLayoutTest();
        }
    }
    

    Running the program will show you this:

    border layout java example

    Take note that the button take that the default is to take the entire space of the cell. Like for example, if you want our center button to be 100×50 only in size, we can then place first the button in a panel and add the panel to the frame. We can then change our example and add some line:

            btnCenter.setPreferredSize(new Dimension(100,50));
            JPanel panel = new JPanel();
            panel.add(btnCenter);
    

    and change:

    frame.add(btnCenter, BorderLayout.CENTER);

    to:

    frame.add(panel, BorderLayout.CENTER);

    giving as an output of this:

    border layout java example 2

    Next tutorial will be about Grid Layout which is another form of Layout Manager.

    Related Post