Swing Examples - Border Layout
The class BorderLayout arranges the components to fit in the five regions: east, west, north, south, and center. Following example showcases the use of BorderLayout.
Example - Usage of Border Layout in Swing Application
SwingTester.java
package com.tutorialspoint;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
BorderLayout layout = new BorderLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
panel.add(new JButton("Center"),BorderLayout.CENTER);
panel.add(new JButton("Line Start"),BorderLayout.LINE_START);
panel.add(new JButton("Line End"),BorderLayout.LINE_END);
panel.add(new JButton("East"),BorderLayout.EAST);
panel.add(new JButton("West"),BorderLayout.WEST);
panel.add(new JButton("North"),BorderLayout.NORTH);
panel.add(new JButton("South"),BorderLayout.SOUTH);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Output
Compile and Run the program and verify the output −
swingexamples_layouts.htm
Advertisements