AWT Notes
AWT Notes
AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical
User Interface (GUI) for java programs.
AWT hierarchy
There are four types of containers available in AWT: Window, Frame, Dialog and Panel.
Window: An instance of the Window class has no border and no title.
Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an
associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding
components. An instance of the Panel class provides a container to which to add components.
1
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text
fields, scrollbars etc.
Example 1:
import java.awt.*;
public class SimpleExample extends Frame
{
SimpleExample()
{
Button b=new Button("Button!!");
b.setBounds(50,50,50,50); // setting button position on screen
Example 2:
import java.awt.*;
class First
{
First()
{
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
First f=new First();
}
}
2
STEPS TO PERFORM EVENT HANDLING:
For registering the component with the Listener, many classes provide the registration methods. For
example:
Button public void addActionListener(ActionListener a){}
MenuItem public void addActionListener(ActionListener a){}
TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
TextArea
o public void addTextListener(TextListener a){}
Checkbox
o public void addItemListener(ItemListener a){}
Choice
o public void addItemListener(ItemListener a){}
List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Example 3:
import java.awt.*;
import java.awt.event.*;
3
public static void main(String args[])
{
new AEvent();
}
}
We can close the AWT Window or Frame by calling dispose() or System.exit() inside windowClosing()
method. The windowClosing() method is found in WindowListener interface
and WindowAdapter class.
import java.awt.*;
import java.awt.event.*; //For Event Handling
class Main_Thread extends WindowAdapter//This class for Window close method
{
Frame f;//create frame instance
Main_Thread()
{
f=new Frame();
f.addWindowListener(this); //Mendatory for Listener
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) //This is method for Window Close Listener
{
f.dispose();
}
4
public static void main(String args[])
{
Main_Thread f=new Main_Thread();
}
}
Points to Remember:
1. While creating a frame (either by instantiating or extending Frame class), Following two
attributes are must for visibility of the frame:
o setSize(int width, int height);
o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then you need to add it to the
frame by using the method - add(Component's Object);
3. You can add the following method also for resizing the frame - setResizable(true);
4. public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.
f.add(firstName);
f.add(lastName);
f.add(dob);
f.add(firstNameTF);
f.add(lastNameTF);
f.add(dobTF);
f.add(sbmt);
f.add(reset);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
EVENT
6
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of source.
Events are generated as result of user interaction with the graphical user interface components. For
example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes an event to happen.
Types of Events
Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires, an
operation completion are the example of background events.
Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism has the code which is known as event handler that is executed when an event
occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received, the listeners process the event a then
returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event. The user interface element is able to delegate the processing of an event to the
separate piece of code. In this model, Listener needs to be registered with the source object so that the
listener can receive the event notification. This is an efficient way of handling the event because the
event notifications are sent only to those listeners that want to receive them.
Points to remember about listener :In order to design a listener class we have to develop some
listener interfaces. These Listener interfaces forecast some public abstract callback methods which
must be implemented by the listener class.
If you do not implement the any if the predefined interfaces then your class can not act as a
listener class for a source object.
7
Callback Methods
These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback methods represent an event
method. In response to an event java jre will fire callback method. All such callback methods are
provided in listener interfaces.
Event Listener
The Event listener represents the interfaces responsible to handle events. Java provides us various
Event listener classes. Every method of an event listener method has a single argument as an object
which is subclass of EventObject class. For example, mouse event listener methods will accept
instance of MouseEvent, where MouseEvent derives from EventObject.
AWT Adapters:
Adapters are abstract classes for receiving various events. The methods in these classes are empty.
These classes exist as convenience for creating listener objects.Following is the list of commonly used
adapters while listening GUI events in AWT.
8
Q1. Write a java program to create a frame containing three buttons (Yes, No, Close).
When button yes or no is pressed, the message "Button Yes/No is pressed" gets
displayed in label control. On pressing CLOSE button frame window gets closed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class First extends JFrame
{
JButton yes, no, close;
JLabel lbl;
First()
{
yes = new JButton ("YES");
no = new JButton ("No");
close = new JButton ("CLOSE");
lbl = new JLabel ("");
setLayout (new FlowLayout());
/*setLayout(new BorderLayout());
add("North", new TextField("Title",50));*/
add (no);
add (close);
add (lbl);
setVisible (true);
//setDefaultCloseOperation(JFrame.EXIT_NO_CLOSE);
ButtonHandler bh = new ButtonHandler ();
yes.addActionListener (bh);
yes.addActionListener (bh);
no.addActionListener (bh);
close.addActionListener (bh);
}
class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent ae)
{
if (ae.getSource () == yes)
{
lbl.setText ("Button Yes is pressed");
}
if (ae.getSource () == no)
{
9
lbl.setText ("Button No is pressed");
}
if (ae.getSource () == close)
{
System.exit (0);
}
}
}
public static void main (String args[])
{
First f= new First ();
}
}
Q2. Write a Java program to create a combo box which includes list of
subjects. Display the selected subject in the text field using Swing.
Answer: In this example a combo box having the list of subjects. When any one of
the records selected from the combo box, it will display on the text field.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public Combo_List ()
{
super(" COMBO LIST");
txtsub = new JTextField();
10
cb1 = new JComboBox();
lblsub = new JLabel(" SELECT SUBJECT:");
sub= new JLabel(" SUBJECT NAME:");
add(lblsub);
add(cb1);
add(txtsub);
add(sub);
setSize(500,300);
setLocation(0,0);
setResizable(false);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lblsub.setBounds(50,50,250,40);
cb1.setBounds(170,50,250,35);
sub.setBounds(50,150,250,40);
txtsub.setBounds(170,150,250,35);
cb1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getStateChange() == ItemEvent.SELECTED)
{
try
{
String no=cb1.getSelectedItem().toString();
txtsub.setText(no);
}
catch (Exception ex)
{
System.out.println("An error Occured");
}
}
}
});
11
}
public static void main(String[] args)
{
new Combo_List ();
}
}
Q3. Write a java program using swing to create a frame having three text fields. Accept number
in first textfield and display previous number in second textfield and next number in the third
textfield.
Answer:
Below example shows how to find previous and next number in different textboxes using java Swing.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class First extends JFrame implements ActionListener
{
JLabel textLabel, Label1, Label2;
JTextField Text1, Text2, Text3;
JButton ok, exit;
JPanel pan1, pan2;
int occurrences = 0, i = 0;
public First()
{
textLabel = new JLabel("Enter Number ",JLabel.CENTER);
Label1 = new JLabel("Previous Number ",JLabel.CENTER);
Label2 = new JLabel("Next Number ",JLabel.CENTER);
Text1 = new JTextField(20);
Text2 = new JTextField(20);
Text3 = new JTextField(20);
setLayout(new FlowLayout());
/*pan1 = new JPanel();
pan1.setLayout(new GridLayout(4,2));
pan1.add(textLabel);
pan1.add(Text1);
pan1.add(Label1);
pan1.add(Text2);
pan1.add(Label2);
pan1.add(Text3);*/
add(textLabel);
add(Text1);
add(Label1);
add(Text2);
add(Label2);
add(Text3);
ok = new JButton("ok");
exit = new JButton("Exit");
12
ok.addActionListener(this);
exit.addActionListener(this);
Example 4. Calculator
13
import java.awt.*;
import java.awt.event.*;
b1.addActionListener(this);
14
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
f.setLayout(null);
f.setVisible(true);
f.setSize(400,350);
}
public void actionPerformed(ActionEvent e)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
if(e.getSource()==b1)
{
t3.setText(String.valueOf(n1+n2));
}
if(e.getSource()==b2)
{
t3.setText(String.valueOf(n1-n2));
}
if(e.getSource()==b3)
{
t3.setText(String.valueOf(n1*n2));
}
if(e.getSource()==b4)
{
t3.setText(String.valueOf(n1/n2));
}
if(e.getSource()==b5)
{
System.exit(0);
}
}
public static void main(String...s)
{
new First();
}
}
15
Example 5: Java program to store a Student Information in a File using
AWT.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
// Creating two JComboboxes one for Branch and one for Section
JComboBox j1, j2;
// Naming the labels and setting the bounds for the labels
l1 = new JLabel("Student Name:");
l1.setBounds(50, 50, 100, 30);
l2 = new JLabel("College Email ID:");
l2.setBounds(50, 120, 120, 30);
l3 = new JLabel("Branch:");
l3.setBounds(50, 190, 50, 30);
l4 = new JLabel("Section:");
l4.setBounds(420, 50, 70, 30);
l5 = new JLabel("Mobile No:");
l5.setBounds(420, 120, 70, 30);
// Creating two JComboBoxes one for selecting branch and other for
16
// selecting the sectionand setting the bounds
j1 = new JComboBox(s1);
j1.setBounds(120, 190, 100, 30);
j2 = new JComboBox(s2);
j2.setBounds(470, 50, 140, 30);
// Creating one button for Saving and other button to close and setting the bounds
b1 = new JButton("Save");
b1.setBounds(150, 300, 70, 30);
b2 = new JButton("close");
b2.setBounds(420, 300, 70, 30);
String s1 = t1.getText();
String s2 = t2.getText();
String s3 = j1.getSelectedItem() + "";
String s4 = j2.getSelectedItem() + "";
String s5 = t3.getText();
if (e.getSource() == b1) {
try {
17
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
18
AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
AWT Button Classs Declaration:
public class Button extends Component implements Accessible
Example:
Lets take an example to create a button and it to the frame by providing coordinates.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is
allowed and the text can not be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("Label Demo");
Label lab1;
lab1=new Label("Welcome to IIMT");
lab1.setBounds(50,50,200,30);
l_Frame.add(lab1); l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}
19
AWT TextField
In Java, AWT contains aTextField Class. It is used for displaying single line text.
TextField Declaration:
public class TextField extends TextComponent
Example:
We are creating two textfields to display single line text string. This text is editable in nature, see the
below example.
import java.awt.*;
class TextFieldDemo1
{
public static void main(String args[])
{
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
}
AWT TextArea
In Java, AWT contains a TextArea Class. It is used for displaying multiple-line text.
TextArea Declaration:
public class TextArea extends TextComponent
Example:
In this example, we are creating a TextArea that is used to display multiple-line text string and allows
text editing as well.
import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
20
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e true or
false. When the checkbox is checked then its state is "on" (true) else it is "off"(false).
Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is checked it
returns true else returns false.
import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1()
{
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}
21
AWT CheckboxGroup
In Java, AWT contains aCheckboxGroup Class. It is used to group a set of Checkbox. When
Checkboxes are grouped then only one box can be checked at a time.
CheckboxGroup Declaration:
public class CheckboxGroup extends Object implements Serializable
Example:
This example creates a checkboxgroup that is used to group multiple checkbox in a single unit. It is
helpful when we have to select single choice among the multiples.
import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo()
{
Frame ck_groupf= new Frame("studytonight ==>CheckboxGroup");
CheckboxGroupobj = new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Yes", obj, true);
ckBox1.setBounds(100,100, 50,50);
Checkbox ckBox2 = new Checkbox("No", obj, false);
ckBox2.setBounds(100,150, 50,50);
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupDemo();
}
}
22
AWT Choice
In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of choices. When a
user selects a particular item from the drop-down then it is shown on the top of the menu.
Choice Declaration:
public class Choice extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating drop-down menu that is used to get user choice from multiple
choices.
import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
}
23
AWT List
In Java, AWT contains a List Class. It is used to represent a list of items together. One or more than
one item can be selected from the list.
List Declaration:
public class List extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating a list that is used to list out the items.
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
}
24
AWT Canvas
In Java, AWT contains a Canvas Class. A blank rectangular area is provided. It is used when a user
wants to draw on the screen.
Declaration:
public class Canvas extends Component implements Accessible
Example:
The canvas is used to provide a place to draw using mouse pointer. We can used it to get user
architectural user input.
import java.awt.*;
public class CanvasDemo1
{
public CanvasDemo1()
{
Frame canvas_f= new Frame("studytonight ==> Canvas");
canvas_f.add(new CanvasDemo());
canvas_f.setLayout(null);
canvas_f.setSize(500, 500);
canvas_f.setVisible(true);
}
public static void main(String args[])
{
new CanvasDemo1();
}
}
class CanvasDemo extends Canvas
{
public CanvasDemo() {
setBackground (Color.WHITE);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillOval(80, 80, 150, 75);
}
}
MOVING BALL
25
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}
26
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}
The call to "super.paint(g)", cleans the screen and if we comment this line we can see
the following effect:
MENU
27
As we know that every top-level window has a menu bar associated with it. This menu bar consists of
various menu choices available to the end user. Further each choice contains list of options which is
called drop down menus. Menu and MenuItem controls are subclass of Menu Component class.
Menu Hierarchy
Menu Controls
Sr. Control & Description
No.
1 MenuComponent
It is the top level class for all menu related controls.
2 MenuBar
The MenuBar object is associated with the top-level window.
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the menu bar.
5 CheckboxMenuItem
CheckboxMenuItem is subclass of MenuItem.
6 PopupMenu
PopupMenu can be dynamically popped up at a specified position within a component.
28
Menu Program Using Cut Copy Paste(CCP) Example:
import javax.swing.*;
import java.awt.event.*;
public class Menu_Example implements ActionListener
{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
Menu_Example(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut); edit.add(copy); edit.add(paste); edit.add(selectAll);
mb.add(file); mb.add(edit); mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
I f(e.getSource()==cut)
ta.cut();
29
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args)
{
new Menu_Example();
}
}
LAYOUT
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 controls
are 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.
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.
The layout manager is associated with every Container object. Each layout manager is an object of the
class that implements the LayoutManager interface.
Following is the list of commonly used controls while designed GUI using AWT.
30
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default layout. It layouts the components in a directional flow.
4 GridLayout
The GridLayout manages the components in form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns the
component vertically, horizontally or along their baseline without requiring the components
of same size.
The FlowLayout class is the most basic of layouts. Using the flow layout, components are added to the
panel one at a time, row by row. If a component doesn’t fit onto a row, it’s wrapped onto the next row.
The flow layout also has an alignment, which determines the alignment of each row. By default, each
row is aligned centered.
Border Layouts
Border layouts behave differently from flow and grid layouts. When you add a component to a panel
that uses a border layout, you indicate its placement as a geographic direction: north, south, east, west,
and center. The components around all the edges are laid out with as much size as they need; the
component in the center, if any, gets any space left over.
31
To use a border layout, you create it as you do the other layouts:
setLayout(new BorderLayout());
Then you add the individual components by using a special add() method:
The first argument to add() is a string indicating the position of the component within the layout:
add(“North”, new TextField(“Title”,50));
add(“South”, new TextField(“Status”,50));
Border layouts can also have horizontal and vertical gaps. Note that the north and south components
extend all the way to the edge of the panel, so the gap will result in less space for the east, right, and
center components. To add gaps to a border layout, include those pixel values as before:
setLayout(new BorderLayout(10,10));
Card Layouts
Card layouts are different from the other layouts. Unlike with the other three layouts, when you add
components to a card layout, they are not all displayed on the screen at once. Card layouts are used to
produce slide shows of components, one at a time.
Generally when you create a card layout, the components you add to it will be other container
components usually panels. You can then use different layouts for those individual “cards” so that
each screen has its own look.
When you add each “card” to the panel, you can give it a name. Then you can use methods defined on
the CardLayout class to move back and forth between different cards in the layout.
For example, here’s how to create a card layout containing three cards:
setLayout(new CardLayout());
Panel one = new Panel()
add(“first”, one);
Panel two = new Panel()
add(“second”, two);
Panel three = new Panel()
add(“third”, three);
show(this, “second”);
32
INSETS
Whereas horizontal gap and vertical gap are used to determine the amount of space between
components in a panel, insets are used to determine the amount of space around the panel itself. The
insets class provides values for the top, bottom, left, and right insets, which are then used when the
panel itself is drawn.
Ex: shows an inset in a GridLayout.
To include an inset, override the insets() method in your class (your Applet class or other class that
serves as a panel):
public Insets insets()
{
return new Insets(10,10,10,10);
}
The arguments to the Insets constructor provide pixel insets for the top, bottom, left, and right edges of
the panel. This particular example provides an inset of 10 pixels on all four sides of the panel.
GRID LAYOUT
33
34