JPanel with BoxLayout

BoxLayout arranges components either in a row or in a column. The BoxLayout constructor requires two arguments. The first is a reference to the container to which the layout manager applies, and the second is a constant that can be either BoxLayout. X_AXIS for a row-wise arrangement or BoxLayout.Y_AXIS for a column-wise arrangement.

Program

1

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.BorderFactory;
import java.awt.FlowLayout;

class Frame extends JFrame {
 
    Frame()
    {
        setTitle("JPanel with BoxLayout");
        setLayout(new FlowLayout());
        setJPanelOne();
        setJPanelTwo();
        setSize(700,250);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJPanelOne()
    {
        JPanel jp = new JPanel();
        jp.setLayout(new BoxLayout(jp,BoxLayout.X_AXIS));
        jp.setBorder(BorderFactory.createTitledBorder("JPanel_1"));
        for(int i=0;i<5;i++)
        {
            jp.add(new JButton("JButton "+i));
        }
        add(jp);
    }
 
    private void setJPanelTwo()
    {
        JPanel jp = new JPanel();
        jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
        jp.setBorder(BorderFactory.createTitledBorder("JPanel_2"));
        for(int i=0;i<5;i++)
        {
            jp.add(new JButton("JButton "+i));
        }
        add(jp);
    }
}

public class Javaapp {
 
    public static void main(String[] args) {
     
       Frame fr = new Frame();
    }
}

Leave a Comment