import java.util.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * @author Remi Forax
 *
 */
public class BorderLayoutExample {

  static void swap(JPanel panel,LayoutManager2 layout,Object[] constraints) {
    layout.invalidateLayout(panel);
    Collections.shuffle(Arrays.asList(constraints));
    for(int i=0;i<constraints.length;i++)
      layout.addLayoutComponent(panel.getComponent(i),constraints[i]);
    layout.layoutContainer(panel);
  }

  public static void main(String[] args) {
    JFrame frame=new JFrame("BorderLayoutExample");
    
    final String[] constraints=new String[]{
      BorderLayout.NORTH,
      BorderLayout.SOUTH,
      BorderLayout.EAST,
      BorderLayout.WEST
    };
    
    final BorderLayout layout=new BorderLayout();
    final JPanel panel=new JPanel(layout);
    for(int i=0;i<constraints.length;i++) {
      JButton button=new JButton("button "+i);
      button.setBackground(new Color(i*64,0,255-i*64));
      panel.add(button);
    }
      
    swap(panel,layout,constraints);
    
    JButton swapButton=new JButton("Swap");
    swapButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        swap(panel,layout,constraints);
      }
    });
    panel.add(swapButton,BorderLayout.CENTER);
    
    frame.setContentPane(panel);
    frame.pack();
    frame.show();
  }
}
