Java Swing How to - Combine FlowLayout and BoxLayout








Question

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

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
/*from w  w w  . j  a v  a2s .co  m*/
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame("This is BOX LAYOUT");
    JPanel panel1 = new JPanel();
    panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
    panel1.setBackground(Color.yellow);

    JPanel panel2 = new JPanel();
    panel2.setLayout(new FlowLayout());
    panel2.setBackground(Color.ORANGE);

    for (int i = 0; i < 5; i++)
      panel1.add(new JCheckBox("CheckBox " + (i + 1)));

    f.add(panel1, BorderLayout.WEST);
    f.add(panel2, BorderLayout.CENTER);
    f.setVisible(true);
    f.setSize(300, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}