• The Layout Manager: Border 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.

    Example:

    package com.javapointers.javase;
    
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    /**
     *
     * @author javapointers
     */
    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();
        }
    }
    
    

    When we run our program, the output will be:

    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:

    Related Post