What is BoxLayout - Java Swing

Java examples for Swing:BoxLayout

Introduction

BoxLayout lays out components either horizontally in one row or vertically in one column.

The following code uses a horizontal BoxLayout to display three buttons.

Demo Code

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("BoxLayout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JPanel hPanel = new JPanel();
    BoxLayout boxLayout = new BoxLayout(hPanel, BoxLayout.X_AXIS);
    hPanel.setLayout(boxLayout);//  ww  w  .  ja  va2  s. c  o m
    for (int i = 1; i <= 3; i++) {
      hPanel.add(new JButton("Button " + i));
    }

    contentPane.add(hPanel, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
  }
}

BoxLayout tries to use the preferred width to all components in a horizontal layout.

BoxLayout tries to use the preferred height in a vertical layout.


Related Tutorials