Layout Manager

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Layout Managers

 While it is possible to lay out Java controls by hand, you generally won’t
want to, for two main reasons.
 First, it is very tedious to manually lay out a large number of components.
 Second, sometimes the width and height information is not yet available
when you need to arrange some control.
 Each Container object has a layout manager associated with it.
 A layout manager is an instance of any class that implements the
LayoutManager interface.
 The layout manager is set by the setLayout( ) method.
 If no call to setLayout( ) is made, then the default layout manager is
used.
 Whenever a container is resized (or sized for the first time), the layout
manager is used to position each of the components within it.
 The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)

 Here, layoutObj is a reference to the desired layout manager.


 If you wish to disable the layout manager and position components
manually, pass null for layoutObj.
 If you do this, you will need to determine the shape and position of each
component manually, using the setBounds( ) method defined by
Component.

 Each layout manager keeps track of a list of components that are stored
by their names.
 The layout manager is notified each time you add a component to a
container.
 Whenever the container needs to be resized, the layout manager is
consulted via its minimumLayoutSize( ) and preferredLayoutSize( )
methods.
 Each component that is being managed by a layout manager contains the
getPreferredSize( ) and getMinimumSize( ) methods.
 These return the preferred and minimum size required to display each
component.

Java has several predefined LayoutManager classes.

FlowLayout
 FlowLayout is the default layout manager.
 This is the layout manager that the preceding examples have used.
 FlowLayout implements a simple layout style, which is similar to how
words flow in a text editor.
 The direction of the layout is governed by the container’s component
orientation property, which, by default, is left to right, top to bottom.
 Therefore, by default, components are laid out line-by-line beginning at
the upper-left corner.
 In all cases, when a line is filled, layout advances to the next line.
 A small space is left between each component, above and below, as well
as left and right.

 Here are the constructors for FlowLayout:


FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
 The first form creates the default layout, which centers components and
leaves five pixels of space between each component.
 The second form lets you specify how each line is aligned.
 Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
These values specify left, center, right, leading edge, and trailing edge
alignment, respectively.
The third constructor allows you to specify the horizontal and vertical space left
betweencomponents in horz and vert, respectively.
Here is a version of the CheckboxDemo applet that uses left-aligned flow
layout:

// Use left-aligned flow layout.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=250 height=200>
</applet>
*/

public class FlowLayoutDemo extends Applet implements ItemListener {


String msg = "";
Checkbox winXP, winVista, solaris, mac;

public void init() {


// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));

winXP = new Checkbox("Windows XP", null, true);


winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

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

// register to receive item events


winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}

// Repaint when status of a check box 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 = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows 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);
}
}
Output:

BorderLayout
 The BorderLayout class implements a common layout style for top-level
windows.
 It has four narrow, fixed-width components at the edges and one large
area in the center.
 The four sides are referred to as north, south, east, and west.
 The middle area is called the center.
 Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)

 The first form creates a default border layout.


 The second allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
 BorderLayout defines the following constants that specify the regions:

 When adding components, you will use these constants with the
following form of add( ), which is defined by Container:

void add(Component compObj, Object region)


Here, compObj is the component to be added, and region specifies where the
component will be added.

Example

// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());

add(new Button("This is across the top."),BorderLayout.NORTH);


add(new Label("The footer message might go
here."),BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);

String msg = "The reasonable man adapts " +


"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";

add(new TextArea(msg), BorderLayout.CENTER);


}
}
Sample output:
GridLayout
 GridLayout lays out components in a two-dimensional 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 numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int
vert)
 The first form creates a single-column grid layout.
 The second form creates a grid layout with the specified number of rows
and columns.
 The third form allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
 Either numRows or numColumns can be zero.
 Specifying numRows as zero allows for unlimited-length columns.
 Specifying numColumns as zero allows for unlimited-length rows.

Here is a sample program that creates a 4×4 grid and fills it in with 15 buttons,
each labeled with its index:
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;

public void init() {


setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", 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));
}
}
}
}

Output generated by the GridLayoutDemo applet:

BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or
horizontally. For this purpose, the BoxLayout class provides four constants. They are
as follows:
Note: The BoxLayout class is found in javax.swing package.

Fields of BoxLayout Class

1. public static final int X_AXIS: Alignment of the components are horizontal from left
to right.
2. public static final int Y_AXIS: Alignment of the components are vertical from top to
bottom.
3. public static final int LINE_AXIS: Alignment of the components is similar to the way
words are aligned in a line, which is based on the ComponentOrientation property of
the container. If the ComponentOrientation property of the container is horizontal,
then the components are aligned horizontally; otherwise, the components are aligned
vertically. For horizontal orientations, we have two cases: left to right, and right to left.
If the value ComponentOrientation property of the container is from left to right,
then the components are rendered from left to right, and for right to left, the
rendering of components is also from right to left. In the case of vertical orientations,
the components are always rendered from top to bottom.
4. public static final int PAGE_AXIS: Alignment of the components is similar to the
way text lines are put on a page, which is based on the ComponentOrientation
property of the container. If the ComponentOrientation property of the container is
horizontal, then components are aligned vertically; otherwise, the components are
aligned horizontally. For horizontal orientations, we have two cases: left to right, and
right to left. If the value ComponentOrientation property of the container is also from
left to right, then the components are rendered from left to right, and for right to left,
the rendering of components is from right to left. In the case of vertical orientations,
the components are always rendered from top to bottom.

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the


components with the given axis.

Example of BoxLayout class with Y-AXIS:

import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame {


Button buttons[];

public BoxLayoutExample1 () {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons will be placed horizontally
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

Output:
Example of BoxLayout class with X-AXIS
FileName: BoxLayoutExample2.java

import java.awt.*;

import javax.swing.*;

public class BoxLayoutExample2 extends Frame {


Button buttons[];

public BoxLayoutExample2() {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons in the output will be aligned vertically
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample2 b=new BoxLayoutExample2();
}
}

Output:

CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
Constructors of CardLayout Class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly Used Methods of CardLayout Class

o public void next(Container parent): is used to flip to the next card of the
given container.
o public void previous(Container parent): is used to flip to the previous card
of the given container.
o public void first(Container parent): is used to flip to the first card of the
given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.

Example of CardLayout Class: Using Default


Constructor
The following program uses the next() method to move to the next card of the
container.

// import statements
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CardLayoutExample1 extends JFrame implements ActionListener


{

CardLayout crd;

// button variables to hold the references of buttons


JButton btn1, btn2, btn3;
Container cPane;

// constructor of the class


CardLayoutExample1()
{

cPane = getContentPane();

//default constructor used


// therefore, components will
// cover the whole area
crd = new CardLayout();

cPane.setLayout(crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);

cPane.add("a", btn1); // first card is the button btn1


cPane.add("b", btn2); // first card is the button btn2
cPane.add("c", btn3); // first card is the button btn3

}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
crd.next(cPane);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();

// size is 300 * 300


crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Output:

When the button named apple is clicked, we get


When the boy button is clicked, we get

Again, we reach the first card of the container if the cat button is clicked, and the
cycle continues.
null Layout
null layout is not a real layout manager. It means that no layout manager is assigned and
the components can be put at specific x,y coordinates.

import java.awt.Container;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {


public static void main(String[] args) {
JFrame frame = new JFrame("Null Layout Manager");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(null);/* ww w . j a v a2s . co m*/

JButton b1 = new JButton("Small Button 1");


JButton b2 = new JButton("this is a test 2...");
contentPane.add(b1);
contentPane.add(b2);

b1.setBounds(10, 10, 100, 20);


b2.setBounds(120, 10, 150, 20);

frame.setBounds(0, 0, 350, 100);


frame.setVisible(true);
}
}

You might also like