Saturday, 30 June 2012

program that demostrate GridBagLayout using applet.

import java.awt.*;

/* <applet code = "gridbag" width=200 height=300 >
   </applet>
*/

public class gridbag extends java.applet.Applet
{
      public static void addComponent(Container container,Component component,int gridx,int gridy,int gridwidth,int gridheight,int fill,int anchor) throws AWTException
      {
            LayoutManager lm = container.getLayout();
            if(!(lm instanceof GridBagLayout))
            {
                  throw new AWTException("Invalid Layout"+lm);
            }
            else
            {

                  GridBagConstraints gbc = new GridBagConstraints();
                  gbc.gridx=gridx;
                  gbc.gridy=gridy;
                  gbc.gridwidth=gridwidth;
                  gbc.gridheight=gridheight;
                  gbc.fill=fill;
                  gbc.anchor=anchor;
                 
                  ((GridBagLayout)lm).setConstraints(component,gbc);
                  container.add(component);
             }
      }
     
      public void init()
      {
            Button b;
            GridBagLayout gb = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            setLayout(gb);
           
            try
            {
                  // ROW ONE-THREE BUTTONS
                  b=new Button("one");
                  addComponent(this,b,0,0,1,1,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
                 
                  b=new Button("two");
                  addComponent(this,b,1,0,1,1,GridBagConstraints.BOTH,GridBagConstraints.CENTER);

                  b=new Button("three");
                  addComponent(this,b,2,0,1,1,GridBagConstraints.BOTH,GridBagConstraints.CENTER);

                  // ROW TWO-THREE BUTTONS
                  b=new Button("FOUR");
                  addComponent(this,b,0,1,2,1,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
                 
                  b=new Button("FIVE");
                  addComponent(this,b,2,1,1,2,GridBagConstraints.BOTH,GridBagConstraints.CENTER);

                  // ROW THREE-TWO BUTTONS
                  b=new Button("SIX");
                  addComponent(this,b,0,2,1,1,GridBagConstraints.BOTH,GridBagConstraints.CENTER);

                  b=new Button("SEVEN");
                  addComponent(this,b,1,2,1,1,GridBagConstraints.BOTH,GridBagConstraints.CENTER);
           }
           catch(Exception e)
           {
                 e.printStackTrace();
           }
      }
}