import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;

import javax.swing.*;

/**
 * @author Remi Forax
 *
 */
public class GridLayoutExample {

  static int count=0;

  public static void main(String[] args) {
    JFrame frame=new JFrame("GridLayoutExample");
    
    final JPanel rowPanel=new JPanel(
      new GridLayout(3,0,1,1));
    rowPanel.setBackground(Color.BLUE);
    final JPanel colPanel=new JPanel(
      new GridLayout(0,3,1,1));
    colPanel.setBackground(Color.RED);
    
    JPanel mainPanel=new JPanel();
    JButton newButton=new JButton("New");
    newButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        int value=count++;
        
        rowPanel.add(new JButton("button "+value));
        rowPanel.revalidate();
        colPanel.add(new JButton("button "+value));
        colPanel.revalidate();
      }
    });
    mainPanel.add(newButton);
    mainPanel.add(rowPanel);
    mainPanel.add(colPanel);
   
    frame.setContentPane(mainPanel);
    frame.pack();
    frame.show();
  }
}
