Java Swing How to - Combine BorderLayout and BoxLayout








Question

We would like to know how to combine BorderLayout and BoxLayout.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
/*  w w w . ja v  a 2  s. co m*/
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;

public class Main {

  public static void main(String[] args) {
    int BTN_COUNT = 3;
    int VERT_GAP = 10;
    int EB_GAP = 5;
    float TITLE_SIZE = 36f;
    String TITLE_TEXT = "This is my Title";

    JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
    titleLabel.setFont(titleLabel.getFont().deriveFont(TITLE_SIZE));
    JPanel titlePanel = new JPanel();
    titlePanel.add(titleLabel);

    JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
    for (int i = 0; i < BTN_COUNT; i++) {
      JButton btn = new JButton("Button " + (i + 1));
      buttonPanel.add(btn);
    }

    JTextArea textArea = new JTextArea(20, 30);

    JPanel mainPanel = new JPanel();
    mainPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP,
        EB_GAP));
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
    mainPanel.add(titlePanel);
    mainPanel.add(Box.createVerticalStrut(VERT_GAP));
    mainPanel.add(buttonPanel);
    mainPanel.add(Box.createVerticalStrut(VERT_GAP));
    mainPanel.add(new JScrollPane(textArea));

    JFrame frame = new JFrame();
    frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

  }
}