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
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.
Leave a Reply