Swing Examples - Box Layout



The class BoxLayout arranges the components in stacked manner to put them on top on each other or in row. It provides flexibility over FlowLayout. Following example showcases the use of BoxLayout.

Example - Usage of Box Layout in Swing Application

SwingTester.java

package com.tutorialspoint;

import java.awt.BorderLayout;
import java.awt.LayoutManager;

import javax.swing.BoxLayout;
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(492, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);  
      panel.setLayout(layout);       
      
      panel.add(new JButton("One"));
      panel.add(new JButton("Two")); 
      panel.add(new JButton("Three"));
      panel.add(new JButton("Four"));         
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

Output

Compile and Run the program and verify the output −

Using BoxLayout
swingexamples_layouts.htm
Advertisements