Java Swing How to - Align Checkbox align in 3 rows with GridLayout








Question

We would like to know how to align Checkbox align in 3 rows with GridLayout.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
/*  w w  w. j  a v a2  s.  co m*/
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    String[] data = { "alist", "arithmetic", "ASCIInumbers", "A", "B",
        "list", "C", "D", "E", "numeral", "G",
        "F" };

    JCheckBox[] checkBox;
    JButton submitButton;
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(5, 5));

    checkBox = new JCheckBox[data.length];
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new GridLayout(0, 4, 5, 5));
    for (int i = 0; i < data.length; i++) {
      checkBox[i] = new JCheckBox(data[i]);
      centerPanel.add(checkBox[i]);
    }
    contentPane.add(centerPanel, BorderLayout.CENTER);

    JPanel footerPanel = new JPanel();
    submitButton = new JButton("Submit");
    footerPanel.add(submitButton);
    contentPane.add(footerPanel, BorderLayout.PAGE_END);

    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);

  }
}