Academic Java    Java Tutorial  >  Swing  >  Composite Layout (BorderLayout, GridLayout)

Composite Layout Example

Java Composite Layout EXAMPLE output A user interface of any complexity will use a variety of layout managers to achieve user-friendliness.

This layout example uses BorderLayout of the container cp, and GridLayout for each of the three panels.
// BorderLayout and GridLayout Example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

class BorderLayoutExample2 {

   public static void main(String[] args) {

      JPanel p0 = new JPanel(new GridLayout(0,1));
      JPanel p1 = new JPanel(new GridLayout(0,1));
      JPanel p2 = new JPanel(new GridLayout(0,1));

      p0.setBorder(new TitledBorder(new LineBorder(Color.orange,5),"Cereals"));
      p1.setBorder(new TitledBorder(new LineBorder(Color.pink,5),"Breads"));
      p2.setBorder(new TitledBorder(new LineBorder(Color.cyan,5),"Cakes"));

      JFrame frame = new JFrame("Confectionary");
      Container cp = frame.getContentPane();

      cp.add(new JLabel("Select Your Preferences",JLabel.CENTER),BorderLayout.NORTH);
      cp.add(p0,BorderLayout.WEST);
      cp.add(p1,BorderLayout.CENTER);
      cp.add(p2,BorderLayout.EAST);

      String[] cereals = new String[]{
         "Coco Pops","Muesli","Cheerios","Ready Brek",
         "Frosties","Sugar Puffs","Shreddies"
      };
      for(int i=0;i<cereals.length;++i) p0.add(new JCheckBox(cereals[i]));

      String[] breads = new String[]{
         "Pitta","Naan","Baguette","Chapati","Focaccia",
         "Granary","Panini","Ciabatta"
      };
      for(int i=0;i<breads.length;++i) p1.add(new JCheckBox(breads[i]));

      String[] cakes = new String[]{
         "Baklava","Strudel","Macaroon","Doughnut","Profiterole"
      };
      for(int i=0;i<cakes.length;++i) p2.add(new JCheckBox(cakes[i]));

      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);

   }
}


* BorderLayout Examples