0% found this document useful (0 votes)
13 views41 pages

AWT Classes

AWT (Abstract Window Toolkit) was Java's first GUI framework. It contains classes like Component, Container, Frame, Panel, and Window for building graphical user interfaces. The Graphics class provides methods for drawing shapes and graphics. Common AWT controls include labels, buttons, checkboxes, lists, and text fields which can be added to containers like frames. Events like action events from buttons can be handled using listeners.

Uploaded by

thejugowda121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views41 pages

AWT Classes

AWT (Abstract Window Toolkit) was Java's first GUI framework. It contains classes like Component, Container, Frame, Panel, and Window for building graphical user interfaces. The Graphics class provides methods for drawing shapes and graphics. Common AWT controls include labels, buttons, checkboxes, lists, and text fields which can be added to containers like frames. Events like action events from buttons can be handled using listeners.

Uploaded by

thejugowda121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

INTRODUCTION TO AWT

AWT (Abstract Window Toolkit) was Java’s first GUI framework, which was
introduced in Java 1.0. It is used to create GUIs (Graphical User Interfaces).

AWT Classes
The AWT framework contains many classes and interfaces using which we can
create GUIs. The AWT package is java.awt. Some of the frequently used AWT
classes are listed below:
INTRODUCTION TO AWT

Component and Container


The Component is the abstract root class for many GUI control classes. Container
is a sub class of Component class. The Component and various Container classes
are arranged in a hierarchy as shown below:
INTRODUCTION TO AWT

Component
Component is the abstract class that encapsulates all the properties of a visual
component. Except for menus, most of the GUI components are inherited from the
Component class.
Container
Container is a sub class of the Component class which can be used to hold other
components. A Container object can hold other Containers also. A Container is
responsible for laying out (positioning) the components.
Panel
Panel class is a concrete sub class of the Container class. A Panel object is a
window without title bar, menu bar and border. Panel is the super class of Applet
class and is capable of holding other components or containers.
Window
Window is a sub class of Container class. A Window creates a top-level container
which can hold other components or containers.
Frame
Frame is a concrete sub class of Window class. The Frame encapsulates a window.
Frame contains a title bar, menu bar, borders and resizable corners. To create stand
alone applications in Java, we generally use Frame.

Frame Class

The Frame class is used to create standard windows. Following are two Frame
class constructors:
Frame()
Frame(String title)
INTRODUCTION TO AWT

Following are some of the frequently used methods of Frame class:


void setSize(int width, int height) – Used to specify the width and height of the
frame window.
void setSize(Dimension reference) – Used to specify the dimensions of the frame
window.
Dimension getSize() – Returns the dimensions of the frame window.
void setVisible(boolean visibleFlag) – Makes the frame window visible or non-
visible based on the boolean parameter.
void setTitle(String title) – Used to set the title of the frame window.
INTRODUCTION TO AWT

Graphics Class
In GUI applications, we can use Graphics class of java.awt package to create
various graphics like lines, rectangles, circles, polygons etc
Let’s look at some of the methods available in the Graphics class:

void drawLine(int startX, startY, endX, endY) – Used to draw a line between twi
points.
void drawRect(int startX, int startY, int width, int height) – Used to draw a
rectangle starting from the top left corner with the given width and height. The
coordinates of the top left corner of the rectangle are startX and startY.
void fillRect(int startX, int startY, int width, int height) – Used to draw a solid
(colored) rectangle with the given parameters.
INTRODUCTION TO AWT

void drawRoundRect(int startX, int startY, int width, int height, int xDiam, int
yDiam) – Used to draw a rounded rectangle whose x-diameter and y-diameter of
the corners is given by xDiam and yDiam respectively.

void fillRoundRect(int startX, int startY, int width, int height, int xDiam, int
yDiam) – Used to draw a solid (colored) rounded rectangle whose x-diameter and
y-diameter of the corners is given by xDiam and yDiam respectively.
void drawOval(int startX, int startY, int width, int height) – Used to draw an
ellipse inside an imaginary rectangle whose dimensions are specified by the given
parameters. We can get a circle by giving the same value for both width and
height.
void fillOval(int startX, int startY, int width, int height) – Used to draw a solid
(colored) ellipse inside an imaginary rectangle whose dimensions are specified by
the given parameters. We can get a circle by giving the same value for both width
and height.
void drawArc(int startX, int startY, int width, int height, int startAngle, int
sweepAngle) – Used to draw an arc inside an imaginary rectangle. The start angle
and the sweep angle are specified by using startAngle and sweepAngle
respectively.
void fillArc(int startX, int startY, int width, int height, int startAngle, int
sweepAngle) – Used to draw a solid (colored) arc inside an imaginary rectangle.
The start angle and the sweep angle are specified by using startAngle and
sweepAngle respectively.
void drawPolygon(int x[], int y[], int numPoints) – Used to draw a polygon whose
x coordinates and y coordinates of the points are specified using the x array and y
array respectively. Number of points are specified using numPoints.
void fillPolygon(int x[], int y[], int numPoints) – Used to draw a solid (colored)
polygon whose x coordinates and y coordinates of the points are specified using
the x array and y array respectively. Number of points are specified using
numPoints.

Following Java code demonstrates various methods from the Graphics


class:
INTRODUCTION TO AWT

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
MyFrame()
{
setSize(600, 400);
setTitle("My Application");
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public void paint(Graphics g)
{
g.drawLine(20, 60, 80, 100);
g.drawRect(100, 60, 80, 40);
g.fillRect(200, 60, 80, 40);
g.drawRoundRect(300, 60, 80, 40, 20, 20);
g.fillRoundRect(400, 60, 80, 40, 20, 20);
g.drawOval(20, 120, 80, 40);
g.fillOval(120, 120, 80, 40);
g.drawArc(220, 120, 80, 40, 90, -90);
g.fillArc(320, 120, 80, 40, 90, -90);
int[] x = {20, 100, 80, 20};
INTRODUCTION TO AWT

int[] y = {200, 180, 240, 260};


g.drawPolygon(x, y, 4);
int[] fillx = {120, 200, 180, 120};
int[] filly = {200, 180, 240, 260};
g.fillPolygon(fillx, filly, 4);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java
Copy

Output of the above program is as shown below:


INTRODUCTION TO AWT

AWT Controls
We can add and remove controls to a Container like Applet and Frame using the
following methods available in the Container class:
Component add(Component ref)
Component remove(Component ref)

Label
A label is a GUI control which can be used to display static text. Label can be
created using the Label class and its constructors which are listed below:

Label()
Label(String str)
INTRODUCTION TO AWT

Label(String str, int how)

The parameter how specifies the text alignment. Valid values are
Label.LEFT,
Label.CENTER or Label.RIGHT
Some of the methods available in the Label class are as follows:
void setText(String str) – To set or assign text to the label.
String getText() – To retrieve the text of a label.
void setAlignment(int how) – To set the alignment of text in a label.
int getAlignment() – To get the alignment of text in a label.

Following example demonstrates working with labels in AWT:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Label myLabel;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
setVisible(true);
myLabel = new Label("This is a label!");
add(myLabel);
addWindowListener(new WindowAdapter()
{
INTRODUCTION TO AWT

public void windowClosing(WindowEvent we)


{
System.exit(0);
}
}
);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java
Copy

Output of above code is as show below:

Buttons

A push button is the frequently found GUI control. A push button or a button can
be created by using the Button class and its constructors which are given below:
INTRODUCTION TO AWT

Button()
Button(String str)

Some of the methods available in the Button class are as follows:


void setLabel(String str) – To set or assign the text to be displayed on the button.
String getLabel() – To retrieve the text on the button.

When a button is clicked, it generates an ActionEvent which can be handled using


the ActionListener interface and the event handling method is actionPerformed().
If there are multiple buttons we can get the label of the button which was clicked
by using the method getActionCommand().

Following Java code demonstrates working with buttons:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Button b1, b2, b3;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
setVisible(true);
b1 = new Button("Red");
b2 = new Button("Green");
b3 = new Button("Blue");
INTRODUCTION TO AWT

add(b1);
add(b2);
add(b3);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is as shown below:


INTRODUCTION TO AWT

Checkboxes

A checkbox control can be created using the Checkbox class and its following
constructors:

Checkbox()
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)

Following are various methods available in the Checkbox class:


boolean getState() – To retrieve the state of a checkbox.
void setState(boolean on)– To set the state of a checkbox.
String getLabel() – To retrieve the text of a checkbox.
void setLabel(String str) – To set the text of a checkbox.

A checkbox when selected or deselected, generates an ItemEvent which can be


handled using the ItemListener interface and the corresponding event handling
method is itemStateChanged().

Following code demonstrates working with checkboxes:

import java.awt.*;
INTRODUCTION TO AWT

import java.awt.event.*;

public class MyFrame extends Frame


{
Checkbox c1, c2;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
setVisible(true);
c1 = new Checkbox("Male");
c2 = new Checkbox("Female");
add(c1);
add(c2);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy
INTRODUCTION TO AWT

Output of the above code is shown below:

In AWT, there is no separate class for creating radio buttons. The difference
between a checkbox and radio button is, a user can select one or more checkboxes.
Whereas, a user can select only one radio button in a group.
Radio buttons can be create by using Checkbox class and CheckboxGroup class as
shown in the below code:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Checkbox c1, c2;
CheckboxGroup cbg;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
setVisible(true);
INTRODUCTION TO AWT

cbg = new CheckboxGroup();


c1 = new Checkbox("Male", cbg, false);
c2 = new Checkbox("Female", cbg, false);
add(c1);
add(c2);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is as shown below:


INTRODUCTION TO AWT

Dropdown Boxes

A drop down box or a combo box contains a list of items (strings). When a user
clicks on a drop down box, it pops up a list of items from which user can select a
single item.
A drop down box can be created using the Choice class. There is only one
constructor in the choice class using which we can create an empty list.
Following are various methods available in Choice class:
void add(String name) – To add an item to the drop down list.
String getSelectedItem() – To retrieve the item selected by the user.
int getSelectedIndex() – To retrieve the index of the item selected by the user.
int getItemCount() – To retrieve the number of items in the drop down list.
void select(int index) – To select an item based on the given index.
void select(String name) – To select an item based on the given item name.
void getItem(int index) – To retrieve an item at the given index.
Whenever an user selects an item from the drop down box, an ItemEvent is
generated. It can be handled using the ItemListener interface and the event
handling method is itemStateChanged().
INTRODUCTION TO AWT

Following code demonstrates working with drop down boxes:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Choice myList;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
setVisible(true);
myList = new Choice();
myList.add("CSE");
myList.add("ECE");
myList.add("EEE");
myList.add("IT");
add(myList);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public static void main(String[] args)
INTRODUCTION TO AWT

{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is:

List Boxes

List box contains a list of items among which the user can select one or more
items. More than one items in the list box are visible to the user. A list box can be
created using the List class along with the following constructors:

List()
List(int numRows)
List(int numRows, boolean multipleSelect)
INTRODUCTION TO AWT

In the above constructors, numRows specifies the number of items to be visible to


the user and multipleSelect specifies whether the user can select multiple items or
not.
When a list item is double clicked, ActionEvent is generated. It can be handled
with ActionListener and the event handling method is actionPerformed(). We can
get the name of the item using getActionCommand() method.
When a list item is selected or deselected, ItemEvent is generated. It can be
handled with ItemListener and the event handling method is itemStateChanged().
We can use getItemSelectable() method to obtain a reference to the object that
raised this event.

Following are some of the methods available in the List class:


void add(String name) – To add an item to the list box.
void add(String name, int index) – To add an item at the specified index in the list
box.
String getSelectedItem() – To get the item name which is selected by the user.
int getSelectedIndex() – To get the item index which is selected by the user.
String[] getSelectedItems() – To retrieve the selected item names by the user.
int[] getSelectedIndexes() – To retrieve the selected item indexes by the user.
int getItemCount() – To retrieve the number of items in the list box.
void select(int index) – To select an item based on the given index.
String getItem(int index) – To retrieve the item at the given index.

Following code demonstrates working with list boxes:

import java.awt.*;
import java.awt.event.*;
INTRODUCTION TO AWT

public class MyFrame extends Frame


{
List myList;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
myList = new List();
myList.add("CSE");
myList.add("ECE");
myList.add("EEE");
myList.add("IT");
add(myList);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
setVisible(true);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy
INTRODUCTION TO AWT

Output of the above code is shown below:

Text Fields

A text field or text box is a single line text entry control which allows the user to
enter a single line of text. a text field can be created using the TextField class along
with its following constructors:
TextField()
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)

In the above constructors numChars specifies the width of the text field, and str
specifies the initial text in the text field.
When an user hits ‘Enter’ key on the keyboard in a text field, an ActionEvent is
generated. It can be handled using ActionListener and the event handling method is
actionPerformed().
INTRODUCTION TO AWT

Whenever an user modifies the text in the text field, a TextEvent is generated
which can be handled using TextListener and the event handling method is
textValueChanged().

Following are various methods available in TextField class:


String getText() – Retrieves the text in the text field.
void setText(String str) – Assigns or sets text in the text field.
String getSelectedText() – Retrieves the selected text in the text field.
void select(int startindex, int endindex) – To select the text in text field from
startindex to endindex – 1.
boolean isEditable() – To check whether the text field is editable or not.
void setEditable(boolean canEdit) – To make a text field editable or non-editable.
void setEchoChar(char ch) – To set the echo character of a text field. This is
generally used for password fields.
boolean echoCharIsSet() – To check whether the echo character for the text field is
set or not.
char getEchoChar() – To retrieve the current echo character.

Following code demonstrates working with text fields:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Label myLabel;
TextField tf;
MyFrame()
{
INTRODUCTION TO AWT

setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
myLabel = new Label("Enter name: ");
tf = new TextField(20);
add(myLabel);
add(tf);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
setVisible(true);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is as shown below:


INTRODUCTION TO AWT

Text Areas

A text area is a multi-line text entry control in which user can enter multiple lines
of text. A text area can be created using the TextArea class along with the
following constructors:

TextArea()
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)

In the above constructors, numLines specifies the height of the text area, numChars
specifies the width of the text area, str specifies the initial text in the text area and
sBars specifies the scroll bars. Valid values of sBars can be any one of the
following:

SCROLLBARS_BOTH
SCROLLBARS_NONE
INTRODUCTION TO AWT

SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

Following are some of the methods available in the TextArea class:


String getText() – To retrieve the text in the text area.
void setText(String str) – To assign or set the text in a text area.
String getSelectedText() – To retrieve the selected text in a text area.
void select(int startindex, int endindex) – To select the text in text field from
startindex to endindex – 1.
boolean isEditable() – To check whether the text field is editable or not.
void setEditable(boolean canEdit) – To make a text field editable or non-editable.
void append(String str) – To append the given string to the text in the text area.
void insert(String str, int index) – To insert the given string at the specified index.
void replaceRange(String str, int startIndex, int endIndex) – To replace the text
from startIndex to endIndex – 1 with the given string.

Following code demonstrates working with text areas:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
TextArea ta;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
INTRODUCTION TO AWT

setLayout(new FlowLayout());
ta = new TextArea(3, 20);
add(ta);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
setVisible(true);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is shown below:


INTRODUCTION TO AWT

Layout Managers:
A layout manager is one which automatically manages the arrangement of various
of components in a container.
Panel – Flow Layout
JPanel – Flow Layout
Applet – Flow Layout
JApplet – Border Layout
Frame – Border Layout
JFrame – Border Layout

A layout manager is an instance of that class which implements


the LayoutManager interface. The layout manager can be set by using
the setLayout() method whose general form is as follows:

void setLayout(LayoutManager layoutObj)

. Different layout managers available in AWT are:

1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
INTRODUCTION TO AWT

5. GridBagLayout

FlowLayout Manager
The flow layout manager arranges the components one after another from left-to-
right and top-to-bottom manner.

layout manager instance can be created using anyone of the following constructors:

FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int hspace, int vspace)

In the above constructors, how specifies the alignment, hspace specifies horizontal
space, and vspace specifies vertical space. Valid values for alignment are as
follows:

FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
Following code demonstrates working with FlowLayout:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Panel p1, p2, p3;
INTRODUCTION TO AWT

Label l1, l2;


TextField t1, t2;
Button b;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
setLayout(new FlowLayout());
p1 = new Panel();
l1 = new Label("Enter Username: ");
t1 = new TextField(20);
p1.add(l1);
p1.add(t1);
p1.setPreferredSize(new Dimension(400, 30));
p2 = new Panel();
l2 = new Label("Enter Password: ");
t2 = new TextField(20);
t2.setEchoChar('*');
p2.add(l2);
p2.add(t2);
p2.setPreferredSize(new Dimension(400, 30));
p3 = new Panel();
b = new Button("Login");
p3.add(b);
add(p1);
add(p2);
add(p3);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
INTRODUCTION TO AWT

System.exit(0);
}
}
);
setVisible(true);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is as shown below:


INTRODUCTION TO AWT

BorderLayout Manager

The border layout manager divides the container area into five regions namely:
north, south, east, west, and center. Default region is center. You have to be careful
with border layout as controls might be stacked over one another. Border layout
instance can be created by using one of the below constructors:

BorderLayout()
BorderLayout(int hspace, int vspace)

In the above constructors, hspace signifies horizontal space between components


and vspace signifies vertical space between components.

Following code demonstrates working with BorderLayout:

import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame


{
Button bnorth, bsouth, beast, bwest, bcenter;
MyFrame()
{
setSize(400, 200);
setTitle("My Application");
bnorth = new Button("North");
bsouth = new Button("South");
beast = new Button("East");
bwest = new Button("West");
bcenter = new Button("Center");
add(bnorth, BorderLayout.NORTH);
INTRODUCTION TO AWT

add(bsouth, BorderLayout.SOUTH);
add(beast, BorderLayout.EAST);
add(bwest, BorderLayout.WEST);
add(bcenter, BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
setVisible(true);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is as shown below:


INTRODUCTION TO AWT

GridLayout Manager

The grid layout manager arranges the components in a 2-dimensional grid. While
creating the instance of GridLayout, we can specify the number of rows and
columns in the grid. Care must be taken with the number of cells in the grid and
the number of components being added to the grid. If they don’t match, we might
get unexpected output.
An instance of GridLayout can be created using one of the following constructors:
GridLayout()
GridLayout(int numRows, int numCols)
GridLayout(int numRows, int numCols, int hspace, int vspace)

In the above constructors, numRows and numCols specifies the number of rows
and columns in the grid, hspace and vsapce specifies the horizontal space and
vertical space between the components.

Following code demonstrates working with GridLayout:

import java.awt.*;
import java.awt.event.*;
INTRODUCTION TO AWT

public class MyFrame extends Frame


{
Button b1, b2, b3, b4;
MyFrame()
{
setSize(300, 300);
setTitle("My Application");
setLayout(new GridLayout(2, 2));
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
add(b1);
add(b2);
add(b3);
add(b4);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
setVisible(true);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
INTRODUCTION TO AWT

Java

Copy

Output of the above code is as shown below:

CardLayout Manager

The card layout manager allows the user to create a deck of cards. Each card can
contain different components. At any instant only one card in the deck can be
displayed.
To implement card layout, we must take a panel which acts as the container for
other cards. Each card in turn can be a panel which can contain different
INTRODUCTION TO AWT

components. Components will be added to the respective cards (panels) and all the
cards will be finally added to the deck (container panel).

The card layout can be instantiated using any one of the following constructors:

CardLayout()
CardLayout(int hspace, int vspace)

When adding the cards (panels) to the deck, the following add() method can be
used:

void add(Component panelRef, Object name)

In the above syntax, name is a string which represents the name of the card
(panel). After adding all the cards (panels) to the deck, we can navigate through the
cards using the following methods available in CardLayout class:

void first(Container deck)


void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)

Following code demonstrates working with CardLayout:

import java.awt.*;
import java.awt.event.*;
INTRODUCTION TO AWT

public class MyFrame extends Frame implements ActionListener


{
Button first, last, next, prev;
Panel bpanel, deck;
Label l1, l2, l3;
Panel card1, card2, card3;
CardLayout cl;
MyFrame()
{
setSize(300, 300);
setTitle("My Application");
first = new Button("First");
last = new Button("Last");
next = new Button("Next");
prev = new Button("Previous");
first.addActionListener(this);
last.addActionListener(this);
next.addActionListener(this);
prev.addActionListener(this);
bpanel = new Panel();
bpanel.add(first);
bpanel.add(last);
bpanel.add(next);
bpanel.add(prev);
add(bpanel, BorderLayout.NORTH);
cl = new CardLayout();
l1 = new Label("This is card 1");
l2 = new Label("This is card 2");
l3 = new Label("This is card 3");
card1 = new Panel();
card2 = new Panel();
INTRODUCTION TO AWT

card3 = new Panel();


card1.add(l1);
card2.add(l2);
card3.add(l3);
deck = new Panel();
deck.setLayout(cl);
deck.add(card1, "card1");
deck.add(card2, "card2");
deck.add(card3, "card3");
add(deck, BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("First"))
cl.first(deck);
else if(ae.getActionCommand().equals("Last"))
cl.last(deck);
else if(ae.getActionCommand().equals("Next"))
cl.next(deck);
else
cl.previous(deck);
}
INTRODUCTION TO AWT

public static void main(String[] args)


{
MyFrame mf = new MyFrame();
}
}

Java

Copy

Output of the above code is as shown below:

You might also like