beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Swing – BorderLayout in Java

By Chaitanya Singh | Filed Under: Swing

Borderlayout has five areas where we can add components, the areas are:
1) PAGE_START
2) PAGE_END
3) LINE_START
4) LINE_END
5) CENTER

borderlayoutareas

In this screenshot we have five buttons that are added to each area of a container. The container has BorderLayout. Button names are same as area names for better understanding, they can be different.

This is the code that generates the output we have seen above:

/* Written By Chaitanya
 * Published on: beginnersbook.com
 */
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;

public class BorderLayoutDemo {
  public static void main(String[] args) {
    JFrame frame = new JFrame("BorderLayoutDemo - Beginnersbook.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container container = frame.getContentPane();

    /* Creating and adding 5 buttons to the each area of Border
     * Layout. Button names are intentionally kept same as 
     * area names for better understanding, they can have any names.
     */
    container.add(new JButton("PAGE_START"), BorderLayout.PAGE_START);
    container.add(new JButton("PAGE_END"), BorderLayout.PAGE_END);
    container.add(new JButton("LINE_START"), BorderLayout.LINE_START);
    container.add(new JButton("LINE_END"), BorderLayout.LINE_END);
    container.add(new JButton("CENTER"), BorderLayout.CENTER);

    //pack() method calculates and assign appropriate size for frame
    frame.pack();
 
    //Making the frame visible
    frame.setVisible(true);
  }
}

Notes:
1) Prior to jdk1.4 the area names were different like PAGE_START was known as NORTH, others were SOUTH, EAST, WEST, and CENTER.
2) You can leave an area empty if you dont want to add any component to it.
3) You can add at max one component per area, however if you want to add more than one components then you can use another container inside an area and then you can add components to it. This is known as nesting of containers.

Enjoyed this post? Try these related posts

  1. Java Swing Tutorial for beginners
  2. Swing – JButton tutorial and examples

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap