Java AWT GridLayout set gap
// GridLayout containing six buttons. import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class Main extends JFrame implements ActionListener { private static final String[] names = { "one", "two", "three", "four", "five", "six" }; private final JButton[] buttons = new JButton[names.length]; private boolean toggle = true; private final Container container; private final GridLayout gridLayout1; private final GridLayout gridLayout2; public Main() { super("GridLayout Demo"); gridLayout1 = new GridLayout(2, 3, 5, 5); // 2 by 3; gaps of 5 gridLayout2 = new GridLayout(3, 2); // 3 by 2; no gaps container = getContentPane();// w ww.j a v a 2 s. c om setLayout(gridLayout1); for (int count = 0; count < names.length; count++) { buttons[count] = new JButton(names[count]); buttons[count].addActionListener(this); add(buttons[count]); } } // handle button events by toggling between layouts @Override public void actionPerformed(ActionEvent event) { if (toggle) { container.setLayout(gridLayout2); }else { container.setLayout(gridLayout1); } toggle = !toggle; container.validate(); // re-lay out container } public static void main(String[] args) { Main Main = new Main(); Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main.setSize(300, 200); Main.setVisible(true); } }