You are on page 1of 11

R.P.

Bhalodia BCA College

CH
3
Layout Managers
Layout means the arrangement of components within the container. In other way
we can say that placing the components at a particular position within the
container. The task of layouting the control is done automatically by the Layout
Manager.

Layout Manager
The layout manager automatically positions all the components within the
container. If we do not use layout manager then also the components are
positioned by the default layout manager. It is possible to layout the controls by
hand but it becomes very difficult because of the following two reasons.
 It is very tedious to handle a large number of controls within the container.
 Often the width and height information of a component is not given when
we need to arrange them.
Java provides us with various layout managers to position the controls. The
properties like size shape and arrangement varies from one layout manager to
other layout manager. When the size of the applet or the application window
changes the size, shape and arrangement of the components also changes in
response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.

1
FlowLayout
FlowLayout is the default layout manager for an applet. This class places
the components in a row that is centered in the available space. If the
components cannot fit in the current row, another row will be started.
This class has three constructors which are as follows:
(1) FlowLayout()
(2) FlowLayout(int align)
(3) FlowLayout(int align, int hgap, int vgap)
Here, the align indicates how the components are aligned in a row. The
horizontal and vertical gap in pixels between will be set through hgap and vgap
The FlowLayout class also defines three constants that can be used as
alignment i.e. LEFT, CENTER and RIGHT.
Methods
int getAlignment():-Gets the alignment for this layout.
int getHgap():-Gets the horizontal gap between components.
int getVgap():-Gets the vertical gap between components.
void layoutContainer(Container target):- Lays out the container.
import java.applet.*;
import java.awt.*;
/*
<applet code="FlowLayoutDemo" width=650 height=350>
</applet>
*/
public class FlowLayoutDemo extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,50,50));
for(int i=0;i<20;i++)
{
if(i<9)
add(new Button("Button 0"+(i+1)));
else
add(new Button("Button "+(i+1)));
}
}
}
BorderLayout
The BorderLayout class allows a programmer to specify the placement of a
component. This is done by using geographic terms i.e. “North”, “South”,
2
“East”, “West” or “Center”. The components are placed around the periphery
with the sizes they require. The components in the center uses the remaining
space.
This class has two constructors are as follows :
(1) BorderLayout()
(2) BorderLayout(int hgap, int vgap)

The first form uses no gaps between the components. The second form
allows you to set the horizontal and vertical gaps between the components with
the help of hgap and vgap.
With BorderLayout class gives a different form of add method used which
is as follows :

void addLayoutComponent(Component comp, Object constraints)


Adds the specified component to the layout, using the specified constraint object.
int getHgap()
Returns the horizontal gap between components.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
void removeLayoutComponent(Component comp)
Removes the specified component from this border layout.

import java.applet.*;
import java.awt.*;
/*
<applet code="BorderLayoutApplet" width=300 height=300></applet>
*/
public class BorderLayoutApplet extends Applet
{
public void init()
{
setLayout(new BorderLayout(20,20));
Button b1 = new Button("North");
Button b2 = new Button("South");
Button b3 = new Button("East");
Button b4 = new Button("West");
Button b5 = new Button("Center");
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(b5,"Center");
}
}
3
CardLayout
The class CardLayout arranges each component in the container as a card.
Only one card is visible at a time, and the container acts as a stack of cards.
Constructors
CardLayout():-Creates a new card layout with gaps of size zero.
CardLayout(int hgap, int vgap):-Creates a new card layout with the
specified horizontal and vertical gaps.

Methods
void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to this card layout's internal table of names.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="CardLayoutDemo" width=500 height=500>


</applet>*/

public class CardLayoutDemo extends Applet implements ActionListener,


MouseListener
{
Checkbox Win98, winNT, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init()
{
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);

cardLO = new CardLayout();


osCards = new Panel();
osCards.setLayout(cardLO);//set panel layout ot card layout
4
Win98 = new Checkbox("Windows 98",null,true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");

//add Window checkbox to a panel


Panel winPan = new Panel();
winPan.add(Win98);
winPan.add(winNT);
//add other Os checkbox to a panel
Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);

//add panels to card deck panel


osCards.add(winPan, "Windows");
osCards.add(otherPan,"Other");
//add cards tp main applet panel
add(osCards);
//register to receiver action events
Win.addActionListener(this);
Other.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
cardLO.next(osCards);
}
public void mouseClicked(MouseEvent me){}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}
public void mouseReleased(MouseEvent me){}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource() == Win)
{
cardLO.show(osCards,"Windows");
}
else
{
cardLO.show(osCards,"Windows");
}
}}
5
GridLayout
GrideLayout lays out components in a 2d grid. When you instantiate a
GridLayout, you define the number of rows and columns. The constructors
supported by GridLayout are shown here:
GridLayout()
GridLayout(int rows,int cols)
GridLayout(int rows, int cols, int horz, int vets)
import java.awt.*;
import java.applet.*;

/*<applet code="GridlayoutDemo" width=500 height=500></applet>*/

public class GridlayoutDemo extends Applet


{
static final int n = 4;
public void init()
{
setLayout(new GridLayout(n,n));
setFont(new Font("Monotype Corsiva",Font.BOLD,24));
for(int i=0;i<n;i++)
{
for(int j=0; j<n; j++)
{
int k=i * n +j;
if(k>0)
{
add(new Button(" "+k));
}
}
}
}
}

6
GridBagLayout with GridBagConstraints
GridBagLayout makes the grid bag useful is that you can specify the relative
placement of components by specifying their position within cell inside a grid.
The key to the grid bag is that each component can be different size and each
row in the fird can have a different number of liked to it.
This is why the layout is called gridbaglayout. It’s collecton of small girds joined
together.
The location and size of each component in a grid bag are determined by a set
constraints linked to it.
The constraints are contained in an object of type GridBagConstrains.
Constraints include the height and width of a cell, and the placement of a
component, its alignment and its anchor point within the cell.
The general procedure for using a grid bag is to first create a new
GridBagLayout object and to make it the current layout mananger.
Then, set the constraints that apply to each component that will be added to the
grid bag.
Finally, add the components to the layout manager. Although GridBagLayout is
a bit more complicated than the other layout managers, it is still quite easy to use
once you understand how it works.
GridBagLayout define only one constructor, which is shown here:
GridBagLayout( )
GridBagLayout defines several methods, of which are protected and not for
general use. There is one method, however that you must use: setConstraints( ).
It is shown here: void setConstraints(Component obj, GridBagLayout cons)
The key to successfully using GridBagLayout is the proper setting of the
constraints, which are stored in a GridBagConstraints object.
GridBagConstraints defines several fields that you can set to govern the size, placement and spacing
of a component. These are shown in table. Several are describe in greater detail in the following
discussion.
Field Purpose
int anchor specifies the location of a component
within a cell. The default is
GridBagConstraints.CENTER
int fill Specifies how a component is resized if
the component is small than its cell.
Valid values are
GridBagConstraints.NONE,
GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL,
GridBagConstraints.BOTH.
int gridheight specifies the height of component in
terms of cells. The default is 1.
int gridwidth specifies the width of component in
7
terms of cells. The default is 1.
int gridx specifies the X coordinate of the cell to
which the component will be added. The
default value is
GridBagConstraints.RELATIVE
int gridy specifies the Y coordinate of the cell to
which the component will be added. The
default value is
GridBagConstraints.RELATIVE
Insets insets Specific the insets. Default insets are all
zero.
int ipadx Specific extra horizontal space that
surrounds a component within a cell. The
default size 0.
int ipady Specific extra vertical space that
surrounds a component within a cell. The
default size 0.
double weightx Specific a weight value that determines
the horizontal spacing between cells and
the edge of the container that holds them.
The default value is 0.0. the greater the
weight, the more space that is allocated if
all values are 0.0, extra space is
distributed evenly between the edges of
the window.
double weighty Specific a weight value that determines
the vertical spacing between cells and the
edge of the container that holds them.
The default value is 0.0. the greater the
weight, the more space that is allocated if
all values are 0.0, extra space is
distributed evenly between the edges of
the window.
GridBagConstraints also defines several static fields that contain standart
constraint values, such as GridBagConstraints.CENTER and
GridBagConstraints.VERTICAL.
When a component is smaller than its cell, you can use the anchor field to specify where within the
cell the component’s top-left corner will be located. There are three types of values that you cam
give to anchor.
GridBagConstraints.CENTER GridBagConstraints..SOUTH
GridBagConstraints.EAST GridBagConstraints.SOUTHEAST
GridBagConstraints.NORTH GridBagConstraints.SOUTHWEST
GridBagConstraints.NORTHEAST GridBagConstraints.WEST
GridBagConstraints.NORTHWEST
8
As their names imply, these values cause the component to be placed at the
specific locations.
//USE gribagLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="GridBagDemo" width=250 height=250>


</applet>*/

public class GridBagDemo extends Applet implements ItemListener


{
String msg=" ";
Checkbox winXP, winVista, solaris, mac;
public void init()
{
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);

//Define the grid box


winXP = new Checkbox("Window XP",null,true);
winVista = new Checkbox("Window Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

//Define the grid bag.


//Use default row weight of 0 for first row.
gbc.weightx = 1.0; //use a column weight of 1
gbc.ipadx = 200; //pad by 200 unit
gbc.insets = new Insets(4,4,0,0);//inset slightly from top left
gbc.anchor = GridBagConstraints.NORTHEAST;

gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(winXP,gbc);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(winVista,gbc);

//give second row a weight of 1


gbc.weighty = 1.0;

gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris,gbc);
9
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac,gbc);

//add the components.


add(winXP);
add(winVista);
add(solaris);
add(mac);

//Register to receive item events.


winXP.addItemListener(this);
winVista.addItemListener(this);
mac.addItemListener(this);
}
//Repaint when status of a check obx changes.
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
//display current state of the check boxes
public void paint(Graphics g)
{
msg = "Current State: ";
g.drawString(msg,6,80);
msg = " Window XP: "+winXP.getState();
g.drawString(msg,6,100);
msg = " Window Vista: "+winVista.getState();
g.drawString(msg,6,120);
msg = " Solaris: "+solaris.getState();
g.drawString(msg,6,140);
msg = " Mac: "+mac.getState();
g.drawString(msg,6,160);
}
}

10
Introduction to BoxLayout,SpringLayout GroupLayout
Using No Layout Manager

11

You might also like