To create a BoxLayout in Java, you need to specify the container on which you want to apply the layout and the desired orientation (horizontal or vertical).
Here's an example:
import javax.swing.*;
public class BoxLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example");
JPanel panel = new JPanel();
// Set the panel's layout manager to BoxLayout
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Add components to the panel
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
// Add the panel to the frame
frame.getContentPane().add(panel);
// Set frame properties and make it visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
This example creates a JFrame with a JPanel that uses a vertical BoxLayout. It adds three JButton components to the panel.