Java Swing How to - Create GroupLayout with manual gaps








Question

We would like to know how to create GroupLayout with manual gaps.

Answer

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*  w  w w  .j  av  a  2s .c om*/
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.LayoutStyle.ComponentPlacement;

public class Main extends JFrame {

  private final JLabel[] labels = { new JLabel("Label 0"),
      new JLabel("Label 1"), new JLabel("Label 2"), new JLabel("Label 3"),
      new JLabel("Label 4"), new JLabel("Label 5"), new JLabel("Label 6"),
      new JLabel("Label 7"), new JLabel("Label 8"), new JLabel("Label 9") };

  public Main() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container pane = getContentPane();
    GroupLayout gl = new GroupLayout(pane);
    pane.setLayout(gl);

    gl.setAutoCreateGaps(true);
    gl.setAutoCreateContainerGaps(true);

    JButton btn = new JButton("Switch");
    btn.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        for (int i = 1; i < 9; i++) {
          labels[i].setVisible(!labels[i].isVisible());
        }
      }
    });

    gl.setHonorsVisibility(false);

    SequentialGroup seqGroup = gl.createSequentialGroup();
    gl.setHorizontalGroup(seqGroup);
    seqGroup.addComponent(btn);
    seqGroup.addPreferredGap(ComponentPlacement.UNRELATED, 10, 10);
    for (int i = 0; i < 10; i++) {
      seqGroup.addComponent(labels[i]);
      seqGroup.addPreferredGap(ComponentPlacement.UNRELATED, 10, 10);
    }
    ParallelGroup parGroup = gl.createParallelGroup();
    gl.setVerticalGroup(parGroup);
    parGroup.addComponent(btn);

    for (int i = 0; i < 10; i++) {
      parGroup.addComponent(labels[i]);
    }
    pack();
  }

  public static void main(String[] args) {
    Main ex = new Main();
    ex.setVisible(true);
  }
}