Set JPanel layout using BoxLayout

Complete source code below will show you how to set JPanel layout using BoxLayout

*******************************************************************
COMPLETE SOURCE CODE FOR : SetJPanelLayoutUsingBoxLayout.java
*******************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJPanelLayoutUsingBoxLayout
{
public static void main(String[]args)
{
//Create a window using JFrame with title ( Set JPanel layout using BoxLayout )
JFrame frame=new JFrame("Set JPanel layout using BoxLayout");

//Create a panel using JPanel
JPanel panel=new JPanel();

//Set JPanel layout using BoxLayout with vertical lay out
//You can try change to BoxLayout.X_AXIS to make components lay out in horizontal
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));

//Create a button with text ( First button )
JButton button=new JButton("First button");

//Create a button with text ( Second button )
JButton button2=new JButton("Second button");

//Create a button with text ( Third button )
JButton button3=new JButton("Third button");

//Create a dimension with :
//Width : 10 pixels
//Height : 10 pixels
Dimension dim=new Dimension(10,10);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//Add button into panel
panel.add(button);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//Add button2 into panel
panel.add(button2);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//Add button3 into panel
panel.add(button3);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//add panel into created JFrame
frame.add(panel);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(500,200);

//Make JFrame locate at center of screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************

RELAXING NATURE VIDEO