Você está na página 1de 72

Chapter - 1

An Overview of the AWT:

The Java programming language class library provides a user interface toolkit called the
Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible.

The Abstract Window Toolkit provides many classes for programmers to use. It is your
connection between your application and the native GUI. The AWT hides you from the
underlying details of the GUI your application will be running on and thus is at very high
level of abstraction. It takes the lowest common denominator approach to retain
portability.

The AWT package enables you to create GUIs in your applets and applications. Different
Windows API from different platforms were looked at and components were identified
that were common to all of them. The AWT API communicates with the platform's native
API's as to give your application the native look and feel. Because they associate with
their own native screen resources, AWT components are called heavyweight components.

Structure of the AWT:

The structure of the AWT is rather simple: Components are added to and then laid out
by layout managers in Containers. We have a variety of event handling, menu, fonts,
graphics classes in addition to those two, but they'll be only briefly discussed here.
Nothing prevents us from using threads, audio, I/O, networking classes alongside the
AWT. The AWT by itself is rather bare and empty. Imagine a text editor that couldn't
save! As a side note, the AWT can be used in a stand-alone Java application or in an
applet that is embedded within a HTML document.

The AWT hierarchy:

Classes:

• BorderLayout
• CardLayout
• CheckboxGroup
• Color
• Component
o Button
o Canvas
o Checkbox
o Choice
o Container
 Panel
 Window
 Dialog
 Frame
o Label
o List
o Scrollbar
o TextCompoment
 TextArea
 TextField
• Dimension
• Event
• FileDialog
• FlowLayout
• Font
• FontMetrics
• Graphics
• GridLayout
• GridBagConstraints
• GridBagLayout
• Image
• Insets
• MediaTracker
• MenuComponent
o MenuBar
o MenuItem
 CheckboxMenuItem
 Menu
• Point
• Polygon
• Rectangle
• Toolkit

Interfaces

• LayoutManager
• MenuComponent

Components and containers

At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component. All user interface
elements that are displayed on the screen and that interact with the user are subclasses of
Component.

Components do not stand alone, but rather are found within Containers. Containers
contain and control the layout of components. Containers are themselves components,
and can thus be placed inside other containers. In the AWT, all containers are instances
of class Container or one of its subtypes.
Types of components

Figure below shows the inheritance relationship between the user interface component
classes provided by the AWT. Class Component defines the interface to which all
components must adhere.

Figure 3. The inheritance relationship

The AWT provides nine basic non-container component classes from which a user
interface may be constructed. These nine classes are class Button, Canvas, Checkbox,
Choice, Label, List, Scrollbar, TextArea, and TextField.

Panel Class

Panel is the simplest container class. A panel provides space in which an application can
attach any other component, including other panels. The default layout manager for a
panel is the FlowLayout layout manager. Panel is the superclass for Applet. When screen
output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a
Panel is a window that does not contain a title bar, menu bar, or border. This is why you
don't see these items when an applet is run inside a browser. When you run an applet
using an applet viewer, the applet viewer provides the title and border.

Panel Class provides only two method of it own they are,


void addNotify()
- Creates the Panel's peer.

AccessibleContext getAccessibleContext()
- Gets the AccessibleContext associated with this Panel.

Other method are inherited from the Component and Container classes like add( ),
setLocation( ), setSize( ), or setBounds( ), setFont( ).

Window Class

A Window object is a top-level window with no borders and no menubar. The default
layout for a window is BorderLayout. A window must have a frame, dialog, or another
window defined as its owner when it's constructed.

It has lot of methods of its own and well as inherites the methods from the Component
and Container class also.

Frame Class

Frame encapsulates what is commonly thought of as a "window". It is a subclass of


Window and has a title bar, menu bar, borders, and resizing corners. If you create a
Frame object from within an applet, it will contain a warning message, such as
"Warning: Applet Window," to the user that an applet window has been created. This
message warns users that the window they see was started by an applet and not by
software running on their computer. The constructors of the Frame class are,

Frame()
Frame(GraphicsConfiguration gc)
Frame(String title)
Frame(String title, GraphicsConfiguration gc)

The first form creates a standard window that does not contain a title. The second form
creates a Frame with the specified GraphicsConfiguration of a screen device. The third
form creates a window with the title specified by title. The fourth form creates frame with
the specified title and a GraphicsConfiguration.

There are several methods provided by Frame class. Let’s see some of them here,

void addNotify()
- Makes this Frame displayable by connecting it to a native screen
resource.

MenuBar getMenuBar()
- Gets the menu bar for this frame.

int getState()
- Gets the state of this frame (obsolete).

String getTitle()
- Gets the title of the frame.

boolean isResizable()
- Indicates whether this frame is resizable by the user.

void remove(MenuComponent m)
- Removes the specified menu bar from this frame.

void removeNotify()
- Makes this Frame undisplayable by removing its connection to its native
screen resource.

void setCursor(int cursorType)


- Deprecated. As of JDK version 1.1, replaced by Component.setCursor.

void setExtendedState(int state)


- Sets the state of this frame.

void setIconImage(Image image)


- Sets the image to be displayed in the minimized icon for this frame.

void setMaximizedBounds(Rectangle bounds)


- Sets the maximized bounds for this frame.

void setMenuBar(MenuBar mb)


- Sets the menu bar for this frame to the specified menu bar.

void setResizable(boolean resizable)


- Sets whether this frame is resizable by the user.

void setState(int state)


- Sets the state of this frame (obsolete).

void setTitle(String title)


- Sets the title for this frame to the specified string.

Let’s see an example for this,

import java.awt.*;
import java.awt.event.*;
public class SimpleFrame extends Frame
{
SimpleFrame()
{
CloseAdapter ca = new CloseAdapter();
setTitle ("Simple Frame");
setSize (300,300);
addWindowListener(ca);
show();
}
public static void main (String args[])
{
new SimpleFrame();
}
}
class CloseAdapter extends WindowAdapter
{
public void windowClosing (WindowEvent event)
{
System.exit (0);
}
}

While compiling and running this program the output will be,

Dialog Class

A Dialog is a top-level window with a title and a border that is typically used to take
some form of input from the user. The size of the dialog includes any area designated for
the border. The dimensions of the border area can be obtained using the getInsets()
method; however, since these dimensions are platform-dependent, a valid insets value
cannot be obtained until the dialog is made displayable by either calling pack or show.
The constructors of Dialog class are,

Dialog(Dialog owner)
Dialog(Dialog owner, String title)
Dialog(Dialog owner, String title, boolean modal)
Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)
Dialog(Frame owner)
Dialog(Frame owner, boolean modal)
Dialog(Frame owner, String title)
Dialog(Frame owner, String title, boolean modal)
Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)

It also provides lot of methods by it own and by inherting from Window, Component,
Object and Container classes. Let see some of the methods provided by Dialog class,

void addNotify()
- Makes this Dialog displayable by connecting it to a native screen
resource.

AccessibleContext getAccessibleContext()
- Gets the AccessibleContext associated with this Dialog.

String getTitle()
- Gets the title of the dialog.

void hide()
- Hides the Dialog and then causes show() to return if it is currently
blocked.

boolean isResizable()
- Indicates whether this dialog is resizable by the user.

void setResizable(boolean resizable)


- Sets whether this dialog is resizable by the user.

void setTitle(String title)


- Sets the title of the Dialog.

void show()
- Makes the Dialog visible.

Let’s see an example for this,

import java.awt.*;
import java.awt.event.*;
public class DialogEx
{
public static void main(String ar[])
{
CloseAdapter ca = new CloseAdapter();
Frame f=new Frame();
f.setTitle("Simple Frame");
f.setSize(300,300);
f.addWindowListener(ca);
f.show();
}
}
class CloseAdapter extends WindowAdapter
{
Dialog d;
public void windowClosing (WindowEvent event)
{
d = new Dialog(new Frame(), "Alert", true);
d.setLayout(new FlowLayout());
Button ok = new Button ("OK");
ok.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
d.setVisible(false);
}
});
d.add(new Label("Click OK to exit"));
d.add( ok );
d.pack();
d.setVisible(true);
System.exit(0);
}
}

While compiling and running this program the output will be,
From the output, you may see that when the close button is pressed in the frame window.
An alert dialog box is open as show in the output. When, you click OK button. The
window gets closed.

Adding and Removing Components:

To add a component in a window, you must first create an instance of the desired
Component and then add it to a window by calling add( ), which is defined
by Container. The add( ) method has several forms. The Common one is,

Component add(Component Obj)

Here, Obj is an instance of the Component that you want to add. Once a Component has
been added, it will automatically be visible whenever its parent window is displayed.

Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove( ). This method is also defined by Container. Its
general form is,

void remove(Component obj)

Here, obj is a reference to the Component you want to remove. You can remove all
Component by calling removeAll( ).

Label Class

A Label object is a component for placing text in a container. A label displays a single line
of read-only text. The text can be changed by the application, but a user cannot edit it
directly. The constructors of the Label class are,

Label( )
Label(String s)
Label(String s, int align)

The first one creates a blank label. The second one creates a label that contains the string
specified by s and the string is left-justified. The third one creates a label that contains the
string specified by s using the alignment specified by align. The value of align must be
one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

You can use the getText() and setText( ) methods of getting and setting the specified
label text. Also you can change and get alignment using getAlignment( ) and
setAlignment( ) methods. Their general forms are,

void setText(String s)
String getText( )
void setAlignment(int align)
int getAlignment( )

Here, align must be one of the alignment constants shown earlier.

Buttons Class

This class creates a labeled button. The application can cause some action to happen
when the button is pushed. The constructors are,

Button( )
Button(String s)

The first version creates an empty button. The second creates a button that contains s as a
label button.

After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). Their general forms are,

void setLabel(String s)
String getLabel( )

Let’s see an example for this,

import java.awt.*;
public class ButtonEx
{
public static void main(String ar[])
{
Frame f=new Frame();
Label l1=new Label("Button One");
Label l2=new Label("Button Two");
Button b1=new Button("1");
Button b2=new Button("2");
f.setTitle("Simple Frame");
f.setLayout(new FlowLayout());
f.setSize(400,400);
f.add(l1);
f.add(b1);
f.add(l2);
f.add(b2);
f.show();
}
}

While compiling and running this program the output will be,
Checkbox and CheckboxGroup Classes

A check box is a graphical component that can be in either an "on" (true) or "off" (false)
state. It consists of a small box that can either contain a check mark or not. There is a
label associated with each check box which represents their identity. You can change the
state of a check box by clicking on it. The Constructors are,

Checkbox()
Checkbox(String lab)
Checkbox(String lab, boolean st)
Checkbox(String lab, boolean st, CheckboxGroup cg)
Checkbox(String lab, CheckboxGroup cg, boolean st)

Here, the first one is the default constructor. The second one create a Checkbox object
with a label lab. The third one creates check box object with label lab and intializate state
st as boolean value true or false. The fourth and fifth create same object type but there
order of arguments only differ, where lab is the label and st is the state and cg is the
CheckboxGroup object, Which associate the checkbox into together using that group
name.

The CheckboxGroup class is used to group together a set of Checkbox buttons. Exactly
one check box button in a CheckboxGroup can be in the "on" state at any given time
which is also called as “radio” buttons. Pushing any button sets its state to "on" and
forces any other button that is in the "on" state into the "off" state. It has only one
constructor,

CheckboxGroup()

The Checkbox and CheckboxGroup classes provides lot of method, some of the widely
used methods are shown below,

void addItemListener(ItemListener l)
- Adds the specified item listener to receive item events from this check
box.

CheckboxGroup getCheckboxGroup()
- Determines this check box's group.

ItemListener[] getItemListeners()
- Returns an array of all the item listeners registered on this checkbox.
String getLabel() Gets the label of this check box.
EventListener[] getListeners(Class listenerType)
- Returns an array of all the objects currently registered as FooListeners
upon this Checkbox.

Object[] getSelectedObjects()
- Returns an array (length 1) containing the checkbox label or null if the
checkbox is not selected.

boolean getState()
- Determines whether this check box is in the "on" or "off" state.

void removeItemListener(ItemListener l)
- Removes the specified item listener so that the item listener no longer
receives item events from this check box.

void setCheckboxGroup(CheckboxGroup g)
- Sets this check box's group to be the specified check box group.

void setLabel(String label)


- Sets this check box's label to be the string argument.

void setState(boolean state)


- Sets the state of this check box to the specified state.

Checkbox getCurrent()
- Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().

Checkbox getSelectedCheckbox()
- Gets the current choice from this check box group.

void setCurrent(Checkbox box)


- Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox.

void setSelectedCheckbox(Checkbox box)


- Sets the currently selected check box in this group to be the specified
check box.

Let’s see this with an example,

import java.awt.*;
public class CheckboxEx
{
public static void main(String ar[])
{
Frame f=new Frame();
CheckboxGroup cg = new CheckboxGroup();
Checkbox c1=new Checkbox("One", true);
Checkbox c2=new Checkbox("Two");
Checkbox c3=new Checkbox("Three", cg, false);
Checkbox c4=new Checkbox("Four", cg, true);
f.setTitle("CheckBox Frame");
f.setLayout(new FlowLayout());
f.setSize(400,100);
f.add(c1);
f.add(c2);
f.add(c3);
f.add(c4);
f.show();
}
}

While compiling and running this program the output will be,

From the example, you can see that the both or any one Checkbox can be selected. But,
you can not select both button in a CheckboxGroup, you can select any one button from
the CheckboxGroup that is if you select one the other get to “off” state.

TextField and TextArea Classes

TextField components are useful for obtaining short pieces of information from users.
They are limited to single line input. Whenever a user types data into a text field, and hits
enter or changes focus, the text field will generate an event. It is also called an edit
control, because you can cut, copy and paste using arrow keys or by using mouse
selections.

TextField()
TextField(int cols)
TextField(String tx)
TextField(String tx, int cols)

Here, the first one is the default constructor. The second one creates a text field with
number of columns specified by cols. The third one creates a text field initialized by the
String tx. The fourth one creates a text field initialized by a String tx and with number of
columns cols.
The TextArea components are useful for getting a large amount of data from a user, or
for displaying a large amount of data that is free to be modified. They take up more
screen real estate than text fields, but can conserve quite a lot of room because they have
support for scrollbars. Like TextField, you can do all edit work in TextArea also. The
constructors of the TextArea class are,

TextArea()
TextArea(int r, int c)
TextArea(String tx)
TextArea(String tx, int r, int c)
TextArea(String tx, int r, int c, int sb)

Here, the first is default constructor. The second one is text area with number of specified
rows r and columns c. The third one is text area which is initialized by a String tx. The
fourth one is text area with specified rows r and columns c and initialized by a String tx.
The last one is same as fourth with one extra argument sb which is the Scrollbar type add
to that text area. The different types of Scrollbar constants are,

static int SCROLLBARS_BOTH


static int SCROLLBARS_HORIZONTAL_ONLY
static int SCROLLBARS_NONE
static int SCROLLBARS_VERTICAL_ONLY

The TextField and TextArea classes provides lot of methods, let’s see some of them here,

void addActionListener(ActionListener l)
- Adds the specified action listener to receive action events from this text
field.

int getColumns()
- Gets the number of columns in this text field.

char getEchoChar()
- Gets the character that is to be used for echoing.

void setColumns(int columns)


- Sets the number of columns in this text field.

void setEchoChar(char c)
- Sets the echo character for this text field.

void setText(String t)
- Sets the text that is presented by this text component to be the specified
text.

void append(String str)


- Appends the given text to the text area's current text.

void appendText(String str)


- Deprecated. As of JDK version 1.1, replaced by append(String).

int getRows()
- Returns the number of rows in the text area.

int getScrollbarVisibility()
- Returns an enumerated value that indicates which scroll bars the text area
uses.

void insert(String str, int pos)


- Inserts the specified text at the specified position in this text area.

void replaceRange(String str, int start, int end)


- Replaces text between the indicated start and end positions with the
specified replacement text.

void setColumns(int columns)


- Sets the number of columns for this text area.

void setRows(int rows)


- Sets the number of rows for this text area.

Let’s see an example for this,

import java.awt.*;
public class TextEx
{
public static void main(String ar[])
{
String s="Hello this is example\ntext for text area";
Frame f=new Frame();
TextField t1=new TextField();
TextField t2=new TextField("Example Text");
TextArea t3=new TextArea(4,25);
TextArea t4=new TextArea(s,4,25);
f.setTitle("Text Frame");
f.setLayout(new FlowLayout());
f.setSize(300,300);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(t4);
f.show();
}
}

While compiling and running this program the output will be,

Choice and List Classes

The Choice class presents a pop-up menu of choices. The current choice is displayed as
the title of the menu. Choice components take up very little screen space, and can present
the user with a series of choice from which a single selection can be made. When the user
clicks on it, the whole list of choices pops up, and a new selection can be made. It has
only one constructor format as show below,

Choice ( )

List components fulfill much the same functionality as choice components. Items can be
added, and the currently selected item can be returned. The List component presents the
user with a scrolling list of text items. The list can be set up so that the user can choose
either one item or multiple items. The constructors of the List class are,

List ( )
List (int rows)
List (int rows, boolean multipleMode)

The Choice and List classes provides lot of methods, let’s see some of them,

void add(String item)


- Adds an item to this Choice or List menu.

String getItem(int index)


- Gets the string at the specified index in this Choice or List menu.
int getItemCount()
- Returns the number of items in this Choice or List menu.

int getSelectedIndex()
- Returns the index of the currently selected item.

String getSelectedItem()
- Gets a representation of the current choice as a string from Choice or List
menu.

void insert(String item, int index)


- Inserts the item into this choice at the specified position.

void select(int pos)


- Sets the selected item in this Choice menu to be the item at the specified
position.

void select(String str)


- Sets the selected item in this Choice menu to be the item whose name is
equal to the specified string.

void add(String item, int index)


- Adds the specified item to the scrolling list at the position indicated
by the index.

String[] getItems()
- Gets the items in the list.

int getRows()
- Get the number of visible lines in this list.

int[] getSelectedIndexes()
- Gets the selected indexes on the list.

String[] getSelectedItems()
- Get the selected items on this scrolling list.

void remove(int position)


- Remove the item at the specified position from this scrolling List or form
Choice.

void remove(String item)


- Removes the first occurrence of an item from the List or Choice menu.

void removeAll()
- Removes all items from this List or Choice menu.
void replaceItem(String newValue, int index)
- Replaces the item at the specified index in the scrolling list with the new
string.

Let’s see an example for these classes,

import java.awt.*;
public class ChoiceListEx
{
public static void main(String ar[])
{
Frame f=new Frame();
Choice c = new Choice();
f.add(c);
c.addItem("Delhi");
c.addItem("Kolkata");
c.addItem("Mumbai");
c.addItem("Bengaluru");
c.addItem("Chennai");
List l = new List(3,true);
f.add(l);
l.addItem("Apple");
l.addItem("Orange");
l.addItem("Grapes");
l.addItem("Mango");
l.addItem("Strawberry");
f.setTitle("Choice_List Frame");
f.setLayout(new FlowLayout());
f.setSize(400,100);
f.show();
}
}

While compiling and running this program the output will be,

From the output, you can see that the Choice shows only one select item at a time, but in
List we can select multiple choices at a same time as shown in the output.

Scrollbar Class
The Scrollbar class embodies a scroll bar, a familiar user-interface object. A scroll bar
provides a convenient means for allowing a user to select from a range of values. Scroll
bars may be oriented horizontally or vertically. A scroll bar is actually a composite of
several individual parts. Each end has an arrow that you can click to move the current
value of the scroll bar one unit in the direction of the arrow. The current value of the
scroll bar relative to its minimum and maximum values is indicated by the slider box for
the scroll bar. The slider box can be dragged by the user to a new position. The scroll bar
will then reflect this value. The constructors of the Scrollbar class are,

Scrollbar()
Scrollbar(int orien)
Scrollbar(int orien, int value, int visible, int min, int max)

Here, the first one is a default constructor. The second and third constructros allow you to
specify the orientation of the scroll bar orient. The orientation can be HORIZONTAL or
VERTICAL In the third constructor; the initial value of the scroll bar is passed in Value.
The number of units represented by the height of the thumb is passed in Visible. The
minimum and maximum values for the scroll bar are specified by min and max.

Some of the methods provided by the Scrollbar class are,

int getBlockIncrement()
- Gets the block increment of this scroll bar.

int getMaximum()
- Gets the maximum value of this scroll bar.

int getMinimum()
- Gets the minimum value of this scroll bar.

int getUnitIncrement()
- Gets the unit increment for this scrollbar.

int getValue()
- Gets the current value of this scroll bar.

int getVisibleAmount()
- Gets the visible amount of this scroll bar.

void setBlockIncrement(int v)
- Sets the block increment for this scroll bar.

void setMaximum(int newMaximum)


- Sets the maximum value of this scroll bar.
void setMinimum(int newMinimum)
- Sets the minimum value of this scroll bar.
void setUnitIncrement(int v)
- Sets the unit increment for this scroll bar.

void setValue(int newValue)


- Sets the value of this scroll bar to the specified value.

void setValues(int value, int visible, int minimum, int maximum)


- Sets the values of four properties for this scroll bar: value,
visibleAmount, minimum, and maximum.

Let’ see an example for this,

import java.awt.*;
public class ScrollbarEx
{
public static void main(String ar[])
{
Frame f=new Frame();
Scrollbar ver = new Scrollbar(Scrollbar.VERTICAL);
Scrollbar hor = new Scrollbar(Scrollbar.HORIZONTAL);
f.add(ver);
f.add(hor);
f.setTitle("Scrollbar Frame");
f.setLayout(new FlowLayout());
f.setSize(400,100);
f.show();
}
}

While compiling and running this program the output will be,

From the program, you can see that two Scrollbar object ver and hor are created and
their orientation is set to be VERTICAL and HORIZONTAL and add to the frame.
They are displayed according to their orientation in the frame as shown in the output.

MenuBar and Menu Class


The MenuBar class encapsulates the platform's concept of a menu bar bound to a frame.
In order to associate the menu bar with a Frame object, call the frame's setMenuBar
method. It has only one constructor as shown below,
MenuBar ( )

A Menu object is a pull-down menu component that is deployed from a menu bar. A
Menu can optionally be a tear-off menu. A tear-off menu can be opened and dragged
away from its parent menu bar or menu. It remains on the screen after the mouse button
has been released.

Each item in a menu must belong to the MenuItem class. It can be an instance of
MenuItem, a submenu, or a check box. The constructors of the Menu class are,

Menu()
Menu(String label)
Menu(String label, boolean tearOff)

Some of the methods provided by the Menu class are,

MenuItem add(MenuItem mi)


- Adds the specified menu item to this menu.

void add(String label)


- Adds an item with the specified label to this menu.

int countItems()
- Deprecated. As of JDK version 1.1, replaced by getItemCount().

MenuItem getItem(int index)


- Gets the item located at the specified index of this menu.

int getItemCount()
- Get the number of items in this menu.

void insert(MenuItem menuitem, int index)


- Inserts a menu item into this menu at the specified position.

void insert(String label, int index)


- Inserts a menu item with the specified label into this menu at the
specified position.

void remove(int index)


- Removes the menu item at the specified index from this menu.

void remove(MenuComponent item)


- Removes the specified menu item from this menu.

void removeAll()
- Removes all items from this menu.

Let’s see an example for this,

import java.awt.*;
public class MenuEx
{
public static void main(String ar[])
{
Frame f=new Frame();
MenuBar mb = new MenuBar();
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
m1.add(new MenuItem("New"));
m1.add(new MenuItem("Open"));
m1.add(new MenuItem("Save"));
m2.add(new MenuItem("Cut"));
m2.add(new MenuItem("Copy"));
m2.add(new MenuItem("Paste"));
mb.add(m1);
mb.add(m2);
f.setMenuBar(mb);
f.setTitle("Menu Frame");
f.setLayout(new FlowLayout());
f.setSize(400,200);
f.show();
}
}

While compiling and running this program the output will be,

From the output, you can see two menus are created and while click on them shows the
items they have.
Working with Applet Class

An applet is a small program that is intended not to be run on its own, but rather to be
embedded inside another application. The Applet class must be the superclass of any
applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The
Applet class provides a standard interface between applets and their environment.

Applets can be used to provide dynamic user-interfaces, and a variety of graphical effects
for web pages. To create an applet, we extend the java.applet.Applet class. Applet has
only the default constructor of it as shown below,

Applet ( )

Life Cycle Methods of Applet

Applet class contain 4 life cycle methods as shown below, and the life cycle diagram is
also shown below,

• public void init()


• public void start()
• public void stop()
• public void destroy

start()

destroy(
init()
)

stop()

init()

This is one of the predefined methods present in the Applet class and it is called by the
browser only once, when you make the 1st request. In this method you can write a block
of codes which will perform one time operations such as opening a file, database
connection, initialization of parameters etc.

start()

This method is execute later the init() method. The start() method calling each and
every time , while reading the block of statements from the file, reading the records from
the database, modification of initialization parameters.

stop()

This method will be called by the browser when we minimize the window where the
applications are running. In the stop() method you can write the block of statements
which will releases the resource temporally.

destroy()

This method will be called by the browser automatically when we close or terminate the
browser window where the applet application is running. In this method we write the
block of statements which will release the resources permanently.

Graphics Class

The AWT supports a rich assortment of graphics methods. All graphics are drawn
relative to a window. This can be the main window of an applet, a child window of an
applet, or a stand-alone application window. The Graphics class is the abstract base class
for all graphics contexts that allow an application to draw onto components that are
realized on various devices, as well as onto off-screen images. Each shape can be drawn
edge-only or filled. Let’s see graphics methods provided by Graphics class in detail here,

drawLine()

The drawLine( ) method is used to draw a line in the applet window, their general form
is,

void drawLine (int X1, int Y1, int X2, int Y2)

Here, x1 and y1 are starting coordinates from where the line starts and x2 and y2 are the
ending coordinates where line ends.

drawRect ( ) and fillRect ( )

The drawRect( ) is used to draw a rectangle for the given values and fillRect( ) is used to
draw a filled rectangle, respectively. Their general form is shown here,

void drawRect(int x, int y, int w, int h)


void fillRect(int x, int y, int w, int h)

Here, x and y are the top left corner point, w is the width of the rectangle and h is the
height of the rectangle.
drawRoundRect() and fillRoundRect()

To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ). Their general


form is shown below,

void drawRoundRect(int x, int y, int w, int h, int xD, int yD)


void fillRoundRect(int x, int y, int w, int h, int xD, int yD)

Here, xD and yD are the diameter of the rounding arc.

Let see an example for these methods,

import java.awt.*;
import java.applet.*;
public class AppEx1 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(20,20,250,20);
g.drawRect(60, 60, 40, 60);
g.fillRect(200, 60, 40, 60);
g.drawRoundRect(60,200 , 40, 60, 25, 25);
g.fillRoundRect(200, 200, 40, 60, 25, 25);
}
}
/*
<applet code="AppEx1.class" width=300 height=300>
</applet>
*/

Compile and running an applet program is not similar as the other application programs.
First you have to compile it using javac. Then for running you have to run using a
browser, or by using the appletviewer.
drawOval( ) and fillOval( )

The drawOval( ) and fillOval( ) methods are used to draw an Oval in an applet. Their
general forms are,

void drawOval(int x, int y, int w, int h)


void fillOval(int x, int y, int w, int h)

Here, x and y are the origin of the oval and w and h are width and height of the oval. To
draw a circle, the width and height should be same.

drawArc( ) and fillArc( )

To draw an arc drawArc( ) and fillArc( ) are used. Their general forms are,

void drawArc(int x, int y, int w, int h, int startAngle, int sweepAngle)


void fillArc(int x, int y, int w, int h, int startAngle, int sweepAngle)

Here, x and y are the origin point of the arc and w and h are the width and height of the
arc. startAngle is from where the arc starts and sweepAngle is the angular distance
where the arc ends.

Let’s see an example for oval and arc methods,

import java.awt.*;
import java.applet.*;
public class OvalArcEx extends Applet
{
public void paint(Graphics g)
{
g.drawOval(20, 20, 40, 60);
g.fillOval(120, 20, 75, 75);
g.drawArc(20, 100, 50, 60, 90, 270);
g.fillArc(120, 100, 45, 45, 0, 230);
}
}
/*
<applet code="OvalArcEx" width=250 height=200>
</applet>
*/

While compiling and running this program the output will be,
drawPolygon() and fillPolygon()

The drawPolygon( ) and fillPolygon( ) method are used to draw a polygon diagram
according to your wish, their general forms are,

void drawPolygon(int x[ ], int y[ ], int n)


void fillPolygon(int x[ ], int y[ ], int n)

Here, x[] and y[] are the array of points for coordinates and n is the number of
coordinates.

Let’s see an example for this,

import java.awt.*;
import java.applet.*;
public class car extends Applet implements Runnable
{
int z=0;
public void start()
{
Thread t=new Thread(this);
t.start();
}
public void run()
{
while(z<500)
{
if(z<400)
{
z=z+20;
repaint();
try
{
Thread.sleep(100);
}
catch(Exception e){ }
}
else
{
z=20;
}
}
}
public void paint(Graphics g)
{
int x1[]={0+z,40+z,50+z,70+z,80+z,120+z,120+z,0+z,0+z};
int y1[]={100,100,80,80,100,100,120,120,100};
int n1=8;
g.fillPolygon(x1,y1,n1);
g.setColor(Color.BLACK);
g.fillOval(10+z,117,15,15);
g.fillOval(90+z,117,15,15);

int x2[]={600-z,640-z,650-z,670-z,680-z,720-z,720-z,600-z,600-z};
int y2[]={300,300,280,280,300,300,320,320,300};
int n2=8;
g.fillPolygon(x2,y2,n2);
g.setColor(Color.BLACK);
g.fillOval(610-z,317,15,15);
g.fillOval(690-z,317,15,15);

}
/*<APPLET CODE="car.class" HEIGHT = 400 WIDTH = 600>
</APPLET>
*/
}

While compiling and running this program the output will be,
Color Class

The Color class is used to encapsulate colors in the default sRGB color space or colors in
arbitrary color spaces identified by a ColorSpace. Every color has an implicit alpha value
of 1.0 or an explicit one provided in the constructor. The alpha value defines the
transparency of a color and can be represented by a float value in the range 0.0 - 1.0 or
0 - 255. An alpha value of 1.0 or 255 means that the color is completely opaque and an
alpha value of 0 or 0.0 means that the color is completely transparent. The constructors of
the Color class are,

Color(ColorSpace cspace, float[] components, float alpha)


Color(float r, float g, float b)
Color(float r, float g, float b, float a)
Color(int rgb)
Color(int rgba, boolean hasalpha)
Color(int r, int g, int b)
Color(int r, int g, int b, int a)

Here, the first constructor has ColorSpace object cspace and floating point components
and an alpha value. The second constructor has floating point value of red r, green g and
blue b. The third constructor has same arguments as second with alpha value. The fourth
one has argument as an integers that specify the color as a mix of red, green, and blue.
The fifth has the mixer value with alpha rgba and a boolean value hasalpha. The sixth
and seventh are similar to second and third but here integer values are used instead of
float.

The Color class provides lot of method, let’s see some of them,

int getAlpha()
- Returns the alpha component in the range 0-255.

int getBlue()
- Returns the blue component in the range 0-255 in the default sRGB
space.

static Color getColor(String nm)


- Finds a color in the system properties.

static Color getColor(String nm, Color v)


- Finds a color in the system properties.

static Color getColor(String nm, int v)


- Finds a color in the system properties.

ColorSpace getColorSpace()
Returns the ColorSpace of this Color.

int getGreen()
- Returns the green component in the range 0-255 in the default sRGB
space.

static Color getHSBColor(float h, float s, float b)


- Creates a Color object based on the specified values for the HSB color
model.

int getRed()
- Returns the red component in the range 0-255 in the default sRGB space.

int getRGB()
- Returns the RGB value representing the color in the default sRGB
ColorModel.

Let’s see an example for this,

import java.awt.*;
import java.applet.*;
public class rocket extends Applet implements Runnable
{
int z=0;
public void start()
{
Thread t=new Thread(this);
t.start();
}
public void run()
{
while(z<500)
{
if(z<400)
{
z=z+20;
repaint();
try
{
Thread.sleep(100);
}
catch(Exception e){ }
}
else
{
z=20;
}
}
}
public void paint(Graphics g)
{
int x1[]={120,100,100,140,140};
int y1[]={320-z,350-z,450-z,450-z,350-z};
int n1=5;
g.setColor(Color.BLUE);
g.fillPolygon(x1,y1,n1);
g.setColor(Color.BLUE);
g.drawLine(100,450-z,100,480-z);

int x2[]={320,300,300,340,340};
int y2[]={320-z,350-z,450-z,450-z,350-z};
int n2=5;
g.setColor(Color.RED);
g.fillPolygon(x2,y2,n2);
g.setColor(Color.RED);
g.drawLine(300,450-z,300,480-z);

}
/*<APPLET CODE="rocket.class" HEIGHT = 500 WIDTH = 500>
</APPLET>
*/
}

While compiling and running this program the output will be,
Font Class

The Font class represents fonts, which are used to render text in a visible way. A font
provides the information needed to map sequences of characters to sequences of glyphs
and to render sequences of glyphs on Graphics and Component objects.

It provides lot of methods let’s see some of them,

static Font createFont(int fontFormat, File fontFile)


- Returns a new Font using the specified font type and the specified font
file.

static Font createFont(int fontFormat, InputStream fontStream)


- Returns a new Font using the specified font type and input data.

static Font decode(String str)


- Returns the Font that the str argument describes.

protected void finalize()


- Disposes the native Font object.

byte getBaselineFor(char c)
- Returns the baseline appropriate for displaying this character.

String getFamily()
- Returns the family name of this Font.

String getFamily(Locale l)
- Returns the family name of this Font, localized for the specified locale.

static Font getFont(String nm)


- Returns a Font object from the system properties list.

static Font getFont(String nm, Font font)


- Gets the specified Font from the system properties list.

String getFontName()
- Returns the font face name of this Font.

String getFontName(Locale l)
- Returns the font face name of the Font, localized for the specified locale.

float getItalicAngle()
- Returns the italic angle of this Font.

String getName()
- Returns the logical name of this Font.

int getSize()
- Returns the point size of this Font, rounded to an integer.

int getStyle()
- Returns the style of this Font.

int hashCode()
- Returns a hashcode for this Font.

boolean isBold()
- Indicates whether or not this Font object's style is BOLD.

boolean isItalic()
- Indicates whether or not this Font object's style is ITALIC.

boolean isPlain()
- Indicates whether or not this Font object's style is PLAIN.

Let’s see an example for this,

import java.applet.*;
import java.awt.*;
public class FontEx extends Applet
{
public void paint(Graphics g)
{
int y=16;
String fonts = "";
String FontList[];
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
{
y=y+20;
fonts = FontList[i];
g.drawString(fonts,4 , y);
}
}
}
/*
<applet code="FontEx" width=550 height=500>
</applet>
*/

While compiling and running this program the output will be,

From the output, you can see that all the fonts in the OS are displayed as a list. There are
ordered by their font family.

Layout Managers
Up to now you have not see how the component added to the container are aligned, for
this different layout technique are used by the container. Layout is controlled not by the
container, but by a layout manager associated with the container. The layout manager
makes all of the component placement decisions. In the AWT, all layout manager classes
implement the LayoutManager interface.

The AWT provides five layout managers. They range from very simple to very complex
layout as show below,

• None - No layout; the Container will not attempt to reposition the Components
during an update.
• FlowLayout - Allows for Component to be laid out in a row and aligned (left,
right, center).
• BorderLayout This scheme lays out the Component in 5 ways
1. North - Northern part of the Container
2. South - Southern part of the Container
3. East - Eastern part of the Container
4. West - Western part of the Container
5. Center - Centered in the Container
• CardLayout - Allows for what Windows programmers have called for years
"tabbed dialogs" or dynamic dialogs.
• GridLayout - Allows for the layout of Components in a grid -like fashion rather
than "North" or "Center".
• GridBagLayout – HTML Table-ish style of layout

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, the layout
manager is used to position each of the components within it. It general form is,

void setLayout(LayoutManager Obj)

Here, Obj is a reference to the desired layout manager you want to set.

Now, we see the FlowLayout and BorderLayout in detail here,

FlowLayout Class

FlowLayout is the default LayoutManager for a Panel. A FlowLayout adds components


to the container in rows, working from left to right. When it can’t fit any more
components in a row, it starts a new row—not unlike a word processor with word wrap
enabled. When the container gets resized, the components within it get repositioned based
on the container’s new size. If sufficient space is available, components within
FlowLayout containers are given their preferred size. If there is insufficient space, you do
not see the components in their entirety. The constructors of the FlowLayout class are,

FlowLayout( )
FlowLayout(int align)
FlowLayout(int align, int hgap, int vgap)

Here, first one is the default constructor. The second one tell the container how to align
the components, using the constants FlowLayout.LEFT, FlowLayout.CENTER,
FlowLayout.RIGHT. The third one allows you to specify the horizontal and vertical
space between components in hgap and vgap, respectively.

The FlowLayout Class provided lot of method, let’s see some of them here,

void addLayoutComponent(String name, Component comp)


- Adds the specified component to the layout.

int getAlignment()
- Gets the alignment for this layout.

int getHgap()
- Gets the horizontal gap between components.

int getVgap()
Gets the vertical gap between components.
oid layoutContainer(Container target)
- Lays out the container.
void removeLayoutComponent(Component comp)
- Removes the specified component from the layout.

void setAlignment(int align)


- Sets the alignment for this layout.

void setHgap(int hgap)


- Sets the horizontal gap between components.

void setVgap(int vgap)


- Sets the vertical gap between components.

Let’s see an example for this,

import java.awt.*;
public class FlowEx
{
public static void main(String ar[])
{
Frame f=new Frame();
Label l1=new Label("Name");
Label l2=new Label("Age");
TextField t1=new TextField(20);
TextField t2=new TextField(20);
Button b1=new Button("Add");
Button b2=new Button("Cancel");
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.setTitle("FlowLayout Frame");
f.setLayout(new FlowLayout());
f.setSize(250,150);
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(b1);
f.add(b2);
f.show();
}
}

While compiling and running this program the output will be,

BorderLayout Class

A Border layout lays out a container, arranging and resizing its components to fit in five
regions: north, south, east, west, and center. Each region may contain no more than one
component, and is identified by a corresponding constant: NORTH, SOUTH, EAST,
WEST, and CENTER. When adding a component to a container with a border layout, use
one of these five constants.

BorderLayout ( )
BorderLayout (int hgap, int gap)

The first one creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in hgap and vgap.

Some of the methods provided by the BorderLayout class are,

void addLayoutComponent(Component comp, Object constraints)


- Adds the specified component to the layout, using the specified
constraint object.

void addLayoutComponent(String name, Component comp)


- If the layout manager uses a per-component string, adds the component
comp to the layout, associating it with the string specified by
name.

int getHgap()
- Returns the horizontal gap between components.

float getLayoutAlignmentX(Container parent)


- Returns the alignment along the x axis.

float getLayoutAlignmentY(Container parent)


- Returns the alignment along the y axis.

int getVgap()
- Returns the vertical gap between components.

void layoutContainer(Container target)


- Lays out the container argument using this border layout.

void removeLayoutComponent(Component comp)


- Removes the specified component from this border layout.

void setHgap(int hgap)


- Sets the horizontal gap between components.

void setVgap(int vgap)


- Sets the vertical gap between components.

Let’s see an example for this,

import java.awt.*;
public class BorderEx
{
public static void main(String ar[])
{
Frame f = new Frame();
f.setLayout(new BorderLayout());
f.add(new Label("North",Label.CENTER),BorderLayout.NORTH);
f.add(new Label("South",Label.CENTER),BorderLayout.SOUTH);
f.add(new Button("Right"), BorderLayout.EAST);
f.add(new Button("Left"), BorderLayout.WEST);
f.setSize(300,300);
f.show();
}
}

While compiling and running this program the output will be,

CardLayout Class

The CardLayout layout manager is significantly different from the other layouts. Whereas
the other layout managers attempt to display all the components within the container at
once, a CardLayout displays only one component at a time. The result is similar to
Netscape Navigator’s Property sheets or a tabbed Dialog, without the tabs. You can flip
through the cards in the layout in order or jump to a specific card if you know its name.
The constructors of the CardLayout class are,

CardLayout( )
CardLayout(int hgap, int vgap)

Here, first one is the default layout. The second one allows you to specify the horizontal
and vertical space left between components in hgap and vgap.

Unlike most other layout managers, CardLayout has a number of instance methods that
programs have to call. Therefore, you usually have to retain a reference to the layout
manager. In addition, you usually have some other component to control the CardLayout.
Most simply, you could put some buttons in a panel and stick this panel in the north
region of a BorderLayout; then make another panel with a CardLayout, and place that in
the center. A more complex task would be to build a set of tabs to control the
CardLayout.

Some of the methods provided by the CardLayout class are,

void addLayoutComponent(Component comp, Object constraints)


- Adds the specified component to this card layout's internal table of
names.

void addLayoutComponent(String name, Component comp)


- Adds the specified component with the specified name to the layout.

void first(Container parent)


- Flips to the first card of the container.

int getHgap()
- Gets the horizontal gap between components.

float getLayoutAlignmentX(Container parent)


- Returns the alignment along the x axis.

float getLayoutAlignmentY(Container parent)


- Returns the alignment along the y axis.

int getVgap()
- Gets the vertical gap between components.

void invalidateLayout(Container target)


- Invalidates the layout, indicating that if the layout manager has cached
information it should be discarded.

void last(Container parent)


- Flips to the last card of the container.

void layoutContainer(Container parent)


- Lays out the specified container using this card layout.

void next(Container parent)


- Flips to the next card of the specified container.

void previous(Container parent)


- Flips to the previous card of the specified container.

void removeLayoutComponent(Component comp)


- Removes the specified component from the layout.

void setHgap(int hgap)


- Sets the horizontal gap between components.

void setVgap(int vgap)


- Sets the vertical gap between components.
void show(Container parent, String name)
- Flips to the component that was added to this layout with the specified
name, using addLayoutComponent.

Let’s see an example for this,

import java.awt.*;
import java.applet.*;
public class CardEx extends Applet
{
CardLayout cl = new CardLayout();
public void init ()
{
setLayout (cl);
Panel p1 = new Panel();
Panel p2 = new Panel();
p1.setLayout (new GridLayout (3, 2));
Choice c = new Choice();
for (int i=1;i<=5;i++)
{
String s="c"+i;
p1.add (new Checkbox(s));
c.addItem(s);
}
p2.add (c);
add ("One", p1);
add ("Two", p2);
}
public boolean action (Event e, Object o)
{
cl.next(this);
return true;
}
}
/*
<Applet code="CardEx" width="200" height="200">
</Applet>*/

While compiling and running this program the output will be,
Here, if you click any of the check box the corresponding choice will been select from
the Choice box of the p2 panel and p1 panel is hidden and p2 panel is now visible as
shown below,

GridLayout Class

The GridLayout layout manager is ideal for laying out objects in rows and columns,
where each cell in the layout has the same size. Components are added to the layout from
left to right, top to bottom. The constructor of the GridLayout class are,

GridLayout( )
GridLayout(int r, int c)
GridLayout(int r, int c, int hgap, int vgap)

Here, first one is the default constructor. The second one creates a grid layout with the
specified number of rows r and columns c. The third one allows you to specify the
horizontal and vertical space left between components in hgap and vgap, respectively.

Some of the methods provided by the GridLayout class are,


void addLayoutComponent(String name, Component comp)
- Adds the specified component with the specified name to the layout.

int getColumns()
- Gets the number of columns in this layout.

int getHgap()
- Gets the horizontal gap between components.

int getRows()
- Gets the number of rows in this layout.

int getVgap()
- Gets the vertical gap between components.

void removeLayoutComponent(Component comp)


- Removes the specified component from the layout.

void setColumns(int cols)


- Sets the number of columns in this layout to the specified value.

void setHgap(int hgap)


- Sets the horizontal gap between components to the specified value.

void setRows(int rows)


- Sets the number of rows in this layout to the specified value.

void setVgap(int vgap)


- Sets the vertical gap between components to the specified value.

Let’s see an example for this,

import java.awt.*;
public class GridEx
{
public static void main(String ar[])
{
Frame f = new Frame();
f.setLayout(new GridLayout(4,3));
for(int i=1;i<=10;i++)
{
f.add(new Button(""+i));
}
f.setSize(200,200);
f.show();
}
}

While compiling and running this program the output will be,

Event Handling Mechanism

Unlike procedural programs, windows-based programs require an event-driven model in


which the underlying environment tells your program when something happens. For
example, when the user clicks on the mouse, the environment generates an event that it
sends to the program. The program must then figure out what the mouse click means and
act accordingly.

There two different event models, or ways of handling events. In Java 1.0.2 and earlier,
events were passed to all components that could possibly have an interest in them. Events
themselves were encapsulated in a single Event class. Java 1.1 implements a “delegation”
model, in which events are distributed only to objects that have been registered to receive
the event. While this is somewhat more complex, it is much more efficient and also more
flexible, because it allows any object to receive the events generated by a component. In
turn, this means that you can separate the user interface itself from the event-handling
code.

In the Java 1.1 event model, all event functionality is contained in a new package,
java.awt.event. Within this package, subclasses of the abstract class AWTEvent represent
different kinds of events. The package also includes a number of EventListener inter
faces that are implemented by classes that want to receive different kinds of events; they
define the methods that are called when events of the appropriate type occur. A number
of adapter classes are also included; they correspond to the EventListener inter faces and
provide null implementations of the methods in the corresponding listener. The adapter
classes aren’t essential but provide a convenient shortcut for developers; rather than
declaring that your class implements a particular EventListener inter face, you can
declare that your class extends the appropriate adapter.

The Delegation Event Model:


The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events. Its concept is
quite simple: a source generates an event and sends it to one or more listeners. In this
scheme, the listener simply waits until it receives an event. Once received, the listener
processes the event and then returns. The advantage of this design is that the application
logic that processes events is cleanly separated from the user interface logic that
generates those events. A user interface element is able to "delegate" the processing of an
event to a separate piece of code.

In the delegation event model, listeners must register with a source in order to receive an
event notification. This provides an important benefit: notifications are sent only to
listeners that want to receive them. This is a more efficient way to handle events than the
design used by the old Java 1.0 approach. Previously, an event was propagated up the
containment hierarchy until it was handled by a component. This required components to
receive events that they did not process, and it wasted valuable time. The delegation
event model eliminates this overhead.

Event Listeners:

A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to
receive and process these notifications.

Event Class

Event is a platform-independent class that encapsulates events from the platform's


Graphical User Interface in the Java 1.0 event model. In Java 1.1 and later versions, the
Event class is maintained only for backwards compatibility. The information in this class
description is provided to assist programmers in converting Java 1.0 programs to the new
event model. The constructors of the Event class are,

Event(Object target, int id, Object arg)


Event(Object target, long when, int id, int x, int y, int key, int mod)
Event(Object target, long when, int id, int x, int y, int key, int mod, Object arg)

At the root of the Java event class hierarchy is EventObject, which is in java.util. It is
the superclass for all events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event.

EventObject contains two methods: getSource( ) and toString( ). The getSource( )


method returns the source of the event. Its general form is shown here:
Object getSource( )

As expected, toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a subclass of


EventObject. It is the superclass (either directly or indirectly) of all AWT-based events
used by the delegation event model. Its getID( ) method can be used to determine the
type of the event. The signature of this method is shown here:

int getID( )

At this point, it is important to know only that all of the other classes discussed in this
section are subclasses of AWTEvent.

The package java.awt.event defines several types of events that are generated by various
user interface elements. Let’s see them in details.

ComponentEvent

A low-level event which indicates that a component moved, changed size, or changed
visibility. Component events are provided for notification purposes ONLY; The AWT
will automatically handle component moves and resizes internally so that GUI layout
works properly regardless of whether a program is receiving these events or not. The
constructor of the ComponentEvent class is,

ComponentEvent(Component source, int id)

This constructor creates a ComponentEvent with the given source; the source is the
object generating the event. The id field identifies the event type. If system generated, the
id will be one of the last four constants above. However, nothing stops you from creating
your own id for your event types.

The ComponentEvent class provides two methods they are,

Component getComponent()
- The getComponent() method returns the source of the event—that is, the
component initiating the event.

String paramString()
- When you call the toString() method of an AWTEvent, the paramString()
method is called in turn to build the string to display.

The constant provided by it are,

COMPONENT_FIRST
COMPONENT_LAST
- The COMPONENT_FIRST and COMPONENT_LAST constants hold
the endpoints of the range of identifiers for ComponentEvent
types.

COMPONENT_HIDDEN
- The COMPONENT_HIDDEN constant identifies component events that
occur because a component was hidden.

COMPONENT_MOVED
- The COMPONENT_MOVED constant identifies component events that
occur because a component has moved.

COMPONENT_RESIZED
- The COMPONENT_RESIZED constant identifies component events
that occurbecause a component has changed size.

COMPONENT_SHOWN
- The COMPONENT_SHOWN constant identifies component events that
occur because a component has been shown.

ContainerEvent

An event which indicates that a container's contents changed because a component was
added or removed. Container events are provided for notification purposes ONLY; The
AWT will automatically handle changes to the containers contents internally so that the
program works properly regardless of whether the program is receiving these events or
not. The constructor of the ContainerEvent class is,

ContainerEvent(Container source, int id, Component child)

The constructor creates a ContainerEvent with the given source, to which the given child
has been added or removed. The id field serves as the identifier of the event type. If
system generated, the id will be one of the constants described previously. However,
nothing stops you from creating your own id for your event types.

The methods provided by ContainerEvent class are,

Container getContainer()
- The getContainer() method returns the container that generated the event.

Component getComponent()
- The getComponent() method returns the component that was added to or
removed from the container.

String paramString()
- When you call the toString() method of an AWTEvent, the paramString()
method is in turn called to build the string to display.

The constants provided by it are,

COMPONENT_ADDED
- This event indicates that a component was added to the container.

COMPONENT_REMOVED
- This event indicates that a component was removed from the container.

CONTAINER_FIRST
- The first number in the range of ids used for container events.

CONTAINER_LAST
- The last number in the range of ids used for container events.

FocusEvent

An event which happens, when a Component has gained or lost the input focus. This low-
level event is generated by a Component. The event is passed to every FocusListener or
FocusAdapter object which registered to receive such events using the Component's
addFocusListener method. Each such listener object gets this FocusEvent when the
event occurs. The constructors of the FocusEvent class are,

FocusEvent(Component source, int id)


FocusEvent(Component source, int id, boolean temporary)
FocusEvent(Component source, int id, boolean temporary, Component opposite)

Here, the first constructor has two arguments, the source component source which you
want to set FocusEvent and identifier id. The second one is same as first with one
boolean value temporary whether the change is temporary are not. The third one has
one extra argument which specifies the component which is opposite to it.

The methods provided by the FocusEvent class are,

boolean isTemporar y()


- The isTemporary() method returns true if the focus event describes a
temporary focus change, false if the event describes a permanent
focus change.

String paramString()
- When you call the toString() method of an AWTEvent, the paramString()
method is in turn called to build the string to display.

getOppositeComponent()
- Returns other component involved in this focus change.

The constants are,

FOCUS_FIRST
FOCUS_LAST
- The FOCUS_FIRST and FOCUS_LAST constants hold the endpoints of
the range of identifiers for FocusEvent types.

FOCUS_GAINED
- The FOCUS_GAINED constant identifies focus events that occur
because a component gains input focus.

FOCUS_LOST
- The FOCUS_LOST constant identifies focus events that occur because a
component loses input focus.

WindowEvent

An event that indicates that a window has changed its status. This event is generated by a
Window object when it is opened, closed, activated, deactivated, iconified, or
deiconified, or when focus is transfered into or out of the Window.

The event is passed to every WindowListener or WindowAdapter object which registered


to receive such events using the window's addWindowListener method. Each such
listener object gets this WindowEvent when the event occurs. The constructors of the
WindowEvent class are,

WindowEvent(Window src, int id)


WindowEvent(Window src, int id, int oldState, int newState)
WindowEvent(Window src, int id, Window opp)
WindowEvent(Window src, int id, Window opp, int oldState, int newState)

This constructor creates a WindowEvent with the given src. The id field serves as the
identifier of the event type. The second construct has two more new arguments the old
state and new state of the window. The third one has another window opp. The fourth is
the combination of the second and third constructors.

The methods provided by the WindowEvent class are,

Window getWindow()
- The getWindow() method returns the Window that generated the event.

String paramString()
- When you call the toString() method of an AWTEvent, the paramString()
method is in turn called to build the string to display.
getNewState()
- For WINDOW_STATE_CHANGED events returns the new state of the
window.

getOldState()
- For WINDOW_STATE_CHANGED events returns the previous state of
the window.

getOppositeWindow()
- Returns the other Window involved in this focus or activation change.

The constants provided are,

WINDOW_FIRST
WINDOW_LAST
- The WINDOW_FIRST and WINDOW_LAST constants hold the
endpoints of the range of identifiers for WindowEvent types.

WINDOW_ICONIFIED
- The WINDOW_ICONIFIED constant identifies window events that
occur because the user iconifies a window.

WINDOW_DEICONIFIED
- The WINDOW_DEICONIFIED constant identifies window events that
occur because the user de-iconifies a window.

WINDOW_OPENED
- The WINDOW_OPENED constant identifies window events that occur
the first time a Frame or Dialog is made visible with show().

WINDOW_CLOSING
- The WINDOW_CLOSING constant identifies window events that occur
because the user wants to close a window.

WINDOW_CLOSED
- The WINDOW_CLOSED constant identifies window events that occur
because a Frame or Dialog has finally closed, after hide() or
destroy().
WINDOW_ACTIVATED
- The WINDOW_ACTIVATED constant identifies window events that
occur because the user brings the window to the front, either after
showing the window, deiconifying, or removing whatever was in front.

WINDOW_DEACTIVATED
- The WINDOW_DEACTIVATED constant identifies window events that
occur because the user makes another window the active window.

InputEvent

It is a root event class for all component-level input events. Input events are delivered to
listeners before they are processed normally by the source where they originated. This
allows listeners and component subclasses to "consume" the event so that the source will
not process them in their default manner. For example, consuming mousePressed events
on a Button component will prevent the Button from being activated. The constructor of
InputEvent is an abstract class with no public constructors.

The methods of the InputEvent class are,

void consume()
- Consumes this event so that it will not be processed in the default
manner by the source which originated it.

int getModifiers()
- Returns the modifier mask for this event.

int getModifiersEx()
- Returns the extended modifier mask for this event.

static String getModifiersExText(int modifiers)


- Returns a String describing the extended modifier keys and mouse
buttons, such as "Shift", "Button1", or "Ctrl+Shift".

long getWhen()
- Returns the timestamp of when this event occurred.

boolean isAltDown()
- Returns whether or not the Alt modifier is down on this event.

boolean isAltGraphDown()
- Returns whether or not the AltGraph modifier is down on this event.

boolean isConsumed()
- Returns whether or not this event has been consumed.

boolean isControlDown()
- Returns whether or not the Control modifier is down on this event.

boolean isMetaDown()
- Returns whether or not the Meta modifier is down on this event.
boolean isShiftDown()
- Returns whether or not the Shift modifier is down on this event.

The Constants are,

ALT_DOWN_MASK
- The Alt key extended modifier constant.

ALT_GRAPH_DOWN_MASK
- The AltGraph key extended modifier constant.

ALT_GRAPH_MASK
- The AltGraph key modifier constant.

ALT_MASK
- The Alt key modifier constant.

BUTTON1_DOWN_MASK
- The Mouse Button1 extended modifier constant.

BUTTON1_MASK
- The Mouse Button1 modifier constant.

BUTTON2_DOWN_MASK
- The Mouse Button2 extended modifier constant.

BUTTON2_MASK
- The Mouse Button2 modifier constant.

BUTTON3_DOWN_MASK
- The Mouse Button3 extended modifier constant.

BUTTON3_MASK
- The Mouse Button3 modifier constant.

CTRL_DOWN_MASK
- The Control key extended modifier constant.

CTRL_MASK
- The Control key modifier constant.

META_DOWN_MASK
- The Meta key extended modifier constant.

META_MASK
- The Meta key modifier constant.
SHIFT_DOWN_MASK
- The Shift key extended modifier constant.

SHIFT_MASK
- The Shift key modifier constant.

KeyEvent

The KeyEvent class is a subclass of InputEvent for dealing with keyboard events.
There are two fundamental key actions: key presses and key releases. These are
represented by KEY_PRESSED and KEY_RELEASED events. Of course, it’s
inconvenient to think in terms of all these individual actions, so Java also keeps track of
the “logical” keys you type. These are represented by KEY_TYPED events. For every
keyboard key pressed, a KeyEvent.KEY_PRESSED event occurs. The constructors of the
KeyEvent class are,

KeyEvent(Component src, int id, long when, int mod, int kCode,
char kChar)
KeyEvent(Component src, int id, long when, int mod, int kCode,
char kChar, int kLocation)

The methods of the KeyEvent class are,

char getKeyChar()
- Returns the character associated with the key in this event.

int getKeyCode()
- Returns the integer keyCode associated with the key in this event.
int getKeyLocation()
- Returns the location of the key that originated this key event.

static String getKeyModifiersText(int modifiers)


- Returns a String describing the modifier key(s), such as "Shift", or
"Ctrl+Shift".

static String getKeyText(int keyCode)


- Returns a String describing the keyCode, such as "HOME", "F1" or "A".

boolean isActionKey()
- Returns whether the key in this event is an "action" key.

String paramString()
- Returns a parameter string identifying this event.

void setKeyChar(char keyChar)


- Set the keyChar value to indicate a logical character.
void setKeyCode(int keyCode)
- Set the keyCode value to indicate a physical key.

There are many other integer constants that are defined by KeyEvent. For example,
VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and letters. Here are some others:

VK_ENTER VK_ESCAPE VK_CANCEL VK_UP


VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL

The VK constants specify virtual key codes and are independent of any modifiers, such
as control, shift, or alt.

MouseEvent

An event which indicates that a mouse action occurred in a component. A mouse action is
considered to occur in a particular component if and only if the mouse cursor is over the
unobscured part of the component's bounds when the action happens. Component bounds
can be obscurred by the visible component's children or by a menu or by a top-level
window. This event is used both for mouse events and mouse motion events. The
constructors of the MouseEvent class are,

MouseEvent(Component src, int id, long when, int mod, int x, int y, int
clickCount, boolean popTrig)
MouseEvent(Component src, int id, long when, int mod, int x, int y, int
clickCount, boolean popTrig, int but)

This constructor creates a MouseEvent with the given source src. The id field serves as
the identifier of the event type. If system-generated, the id will be one of the constants
described in the previous section. However, nothing stops you from creating your own id
for your event types. The when parameter represents the time the event happened. The
modifiers parameter holds the state of the various modifier keys, using the masks defined
for the InputEvent class, and lets you determine which button was pressed. (x, y)
represents the coordinates of the event relative to the origin of source, while clickCount
designates the number of consecutive times the mouse button was pressed within an
indeterminate time period. Finally, the popTrig parameter signifies whether this mouse
event should trigger the display of a PopupMenu, if one is available.

The methods of the MouseEvent class are,

int getButton()
- Returns which, if any, of the mouse buttons has changed state.

int getClickCount()
- Returns the number of mouse clicks associated with this event.

static String getMouseModifiersText(int modifiers)


- Returns a String describing the modifier keys and mouse buttons that
were down during the event, such as "Shift", or "Ctrl+Shift".

Point getPoint()
- Returns the x,y position of the event relative to the source component.

int getX()
- Returns the horizontal x position of the event relative to the source
component.

int getY()
- Returns the vertical y position of the event relative to the source
component.

boolean isPopupTrigger()
- Returns whether or not this mouse event is the popup menu trigger event
for the platform.

String paramString()
- Returns a parameter string identifying this event.

void translatePoint(int x, int y)


- Translates the event's coordinates to a new position by adding specified x
(horizontal) and y (vertical) offsets.

The MouseEvent class defines the following integer constants that can be used to
identify them:

MOUSE_CLICKED The user clicked the mouse.

MOUSE_DRAGGED The user dragged the mouse.

MOUSE_ENTERED The mouse entered a component.

MOUSE_EXITED The mouse exited from a component.

MOUSE_MOVED The mouse moved.

MOUSE_PRESSED The mouse was pressed.

MOUSE_RELEASED The mouse was released.

ActionEvent
A semantic event which indicates that a component-defined action occured. This high-
level event is generated by a component (such as a Button) when the component-specific
action occurs (such as being pressed). The event is passed to every every
ActionListener object that registered to receive such events using the component's
addActionListener method. The constructors of the ActionEvent class are,

ActionEvent(Object src, int id, String cmd)


ActionEvent(Object src, int id, String cmd, int mod)
ActionEvent(Object src, int id, String cmd, long when, int mod)

This constructor creates an ActionEvent with the given src; the source is the object
generating the event. The id field serves as the identifier of the event type. If system-
generated, the id will be ACTION_PERFORMED. However, nothing stops you from
creating your own id for your event types. The cmd parameter is the event’s action
command. Ideally, the action command should be some locale-independent string
identifying the user’s action. Most components that generate action events set this field to
the selected item’s label by default. The second form has event object with modifier key
as extra. The third one has event object with modifier key and timestamp.

The methods of the ActionEvent are,

String getActionCommand()
- Returns the command string associated with this action.

int getModifiers()
- Returns the modifier keys held down during this action event.

long getWhen()
- Returns the timestamp of when this event occurred.

String paramString()
- Returns a parameter string identifying this action event.

The constants of the ActionEvent are,

ACTION_FIRST
ACTION_LAST
- The ACTION_FIRST and ACTION_LAST constants hold the endpoints
of the range of identifiers for ActionEvent types.

ACTION_PERFORMED
- The ACTION_PERFORMED constant represents when a user activates
a component.

ALT_MASK
CTRL_MASK
META_MASK
SHIFT_MASK
- Similar to the mouse events, action events have modifiers. However,
they are not automatically set by the system, so they don’t help you
see what modifiers were pressed when the event occurred.

AdjustmentEvent

The AdjustmentEvent class is another higher-level event class. It encapsulates events that
represent scrollbar motions. When the user moves the slider of a scrollbar or scroll pane,
an AdjustmentEvent passes through the event queue looking for listeners. Although there
is only one type of adjustment event, there are five subtypes represented by constants
UNIT_DECREMENT, UNIT_INCREMENT, and so on. The constructors are,

AdjustmentEvent(Adjustable src, int id, int type, int val)


AdjustmentEvent(Adjustable src, int id, int type, int val, boolean isAdjusting)
Here, the first constructor creates an AdjustmentEvent with the given source; the src is
the object generating the event. The id field serves as the identifier of the event type. If
system-generated, the id of the AdjustmentEvent will be
ADJUSTMENT_VALUE_CHANGED. However, nothing stops you from creating your
own id for your event types. The type parameter is normally one of the five subtypes,
with val being the current setting of the slider, but is not restricted to that. The second
one is same as first with one argument extra with boolean value isAdjusting.

The methods of AdjustmentEvent are,

Adjustable getAdjustable()
- Returns the Adjustable object where this event originated.

int getAdjustmentType()
- Returns the type of adjustment which caused the value changed event.

int getValue()
- Returns the current value in the adjustment event.

boolean getValueIsAdjusting()
- Returns true if this is one of multiple adjustment events.

String paramString()
- Returns a string representing the state of this Event.

The constants of the AdjustmentEvent class are,

ADJUSTMENT_FIRST
ADJUSTMENT_LAST
- The ADJUSTMENT_FIRST and ADJUSTMENT_LAST constants hold
the endpoints of the range of identifiers for AdjustmentEvent
types.

ADJUSTMENT_VALUE_CHANGED
- The ADJUSTMENT_VALUE_CHANGED constant identifies
adjustment events that occur because a user moves the slider of a
Scrollbar or ScrollPane.

UNIT_DECREMENT
- UNIT_DECREMENT identifies adjustment events that occur because
the user selects the increment arrow.

UNIT_INCREMENT
- UNIT_INCREMENT identifies adjustment events that occur because the
user selects the decrement arrow.

BLOCK_DECREMENT
- BLOCK_DECREMENT identifies adjustment events that occur because
the user selects the block decrement area, between the decrement
arrow and the slider.

BLOCK_INCREMENT
- BLOCK_INCREMENT identifies adjustment events that occur because
the user selects the block increment area, between the increment
arrow and the slider.

TRACK
- TRACK identifies adjustment events that occur because the user selects
the slider and drags it.

ItemEvent

The ItemEvent class is another higher-level event class. It encapsulates events that
occur when the user selects a component, like ActionEvent. When the user selects
a checkbox, choice, list item, or checkbox menu item, an ItemEvent passes through the
event queue looking for listeners. Although there is only one type of ItemEvent, there are
two subtypes represented by the constants SELECTED and DESELECTED. The
constructor is,

ItemEvent(ItemSelectable src, int id, Object item, int stateChange)

Here, the constructor creates a ItemEvent with the given source; the source is the object
generating the event. The id field serves as the identifier of the event type. If system-
generated, the id will be ITEM_STATE_CHANGE. However, nothing stops you from
creating your own id for your event types. The item parameter represents the text of the
item selected: for a Checkbox, this would be its label, for a Choice the current selection.

The methods of the ItemEvent class are,

Object getItem()
- Returns the item affected by the event.

ItemSelectable getItemSelectable()
- Returns the originator of the event.

int getStateChange()
- Returns the type of state change (selected or deselected).

String paramString()
- Returns a parameter string identifying this item event.

The constants are,

ITEM_FIRST
ITEM_LAST
- The ITEM_FIRST and ITEM_LAST constants hold the endpoints of the
range of identifiers for ItemEvent types.

ITEM_STATE_CHANGED
- The ITEM_STATE_CHANGED constant identifies item events that
occur because a user selects a component, thus changing its state.

SELECTED
- SELECTED indicates that the user selected the item.

DESELECTED
- DESELECTED indicates that the user deselected the item.

TextEvent

The TextEvent class is yet another higher-level event class. It encapsulates events that
occur when the contents of a TextComponent have changed, although is not required to
have a TextComponent source. When the contents change, either programmatically by a
call to setText() or because the user typed something, a TextEvent passes through the
event queue looking for listeners. The constructor is,

TextEvent(Object source, int id)

Here, the constructor creates a TextEvent with the given source; the source is the object
generating the event. The id field identifies the event type. If systemgenerated, the id will
be TEXT_VALUE_CHANGE. However, nothing stops you from creating your own id
for your event types.

The TextEvent class have only one method as shown below,

String paramString()
- When you call the toString() method of an AWTEvent, the paramString()
method is called in turn to build the string to display.

The constants of TextEvent class are,

TEXT_FIRST
TEXT_LAST
- The TEXT_FIRST and TEXT_LAST constants hold the endpoints of the
range of identifiers for TextEvent types.

TEXT_VALUE_CHANGED
- The TEXT_VALUE_CHANGED constant identifies text events that
occur because a user changes the contents of a text component.

Event Listener Interfaces and Adapters

There are 11 event listener interfaces, which specify the methods a class must implement
to receive different kinds of events. For example, the ActionListener interface defines the
single method that is called when an ActionEvent occurs. These interfaces replace the
various event-handling methods of Java 1.0: action() is now the actionPerformed()
method of the ActionListener interface, mouseUp() is now the mouseReleased() method
of the MouseListener interface, and so on. Most of the listener interfaces have a
corresponding adapter class, which is an abstract class that provides a null
implementation of all the methods in the interface. Rather than implementing a listener
interface directly, you have the option of extending an adapter class and overriding only
the methods you care about. The adapters are available for the listener interfaces with
multiple methods.

ActionListener

The ActionListener interface contains the one method that is called when an
ActionEvent occurs. It has no adapter class. For an object to listen for action events, it is
necessary to call the addActionListener() method with the class that implements the
ActionListener interface as the parameter. The method addActionListener() is
implemented by Button, List, MenuItem, and TextField components.

actionPerformed(ActionEvent e)
The actionPerformed() method is called when a component is selected or activated. Every
component is activated differently; for a List, activation means that the user has double-
clicked on an entry.

AdjustmentListener

The AdjustmentListener interface contains the one method that is called when an
AdjustmentEvent occurs. It has no adapter class. For an object to listen for adjustment
events, it is necessary to call addAdjustmentListener() with the class that implements the
AdjustmentListener interface as the parameter. The addAdjustmentListener() method is
implemented by the Scrollbar component and the Adjustable interface.

adjustmentValueChanged(AdjustmentEvent e)

The adjustmentValueChanged() method is called when a slider is moved. The Scrollbar


and ScrollPane components have sliders, and generate adjustment events when the sliders
are moved.

ComponentListener and ComponentAdapter

The ComponentListener interface contains four methods that are called when a
ComponentEvent occurs; component events are used for general actions on components,
like moving or resizing a component. The adapter class corresponding to
ComponentListener is ComponentAdapter. If you care only about one or two of the
methods in ComponentListener, you can subclass the adapter and override only the
methods that you are interested in. For an object to listen for component events, it is
necessary to call Component.addComponentListener() with the class that implements the
interface as the parameter.

componentResized(ComponentEvent e)
- The componentResized() method is called when a component is resized.

componentMoved(ComponentEvent e)
- The componentMoved() method is called when a component is moved.

componentShown(ComponentEvent e)
- The componentShown() method is called when a component is shown

componentHidden(ComponentEvent e)
- The componentHidden() method is called when a component is hidden

ContainerListener and ContainerAdapter

The ContainerListener interface contains two methods that are called when a
ContainerEvent occurs; container events are generated when components are added to or
removed from a container. The adapter class for ContainerListener is ContainerAdapter.
If you care only about one of the two methods in ContainerListener, you can subclass the
adapter and override only the method that you are interested in. For a container to listen
for container events, it is necessary to call Container.addContainerListener() with the
class that implements the interface as the parameter.

componentAdded(ContainerEvent e)
- The componentAdded() method is called when a component is added to
a container.

componentRemoved(ContainerEvent e)
- The componentRemoved() method is called when a component is
removed from a container.

FocusListener and FocusAdapter

The FocusListener interface has two methods, which are called when a FocusEvent
occurs. Its adapter class is FocusAdapter. If you care only about one of the methods, you
can subclass the adapter and override the method you are interested in. For an object to
listen for a FocusEvent, it is necessar y to call the Component. addFocusListener()
method with the class that implements the FocusListener interface as the parameter.

focusGained(FocusEvent e)
- The focusGained() method is called when a component receives input
focus, usually by the user clicking the mouse in the area of the
component.

focusLost(FocusEvent e)
- The focusLost() method is called when a component loses the input
focus.

ItemListener

The ItemListener interface contains the one method that is called when an ItemEvent
occurs. It has no adapter class. For an object to listen for an ItemEvent, it is necessary to
call addItemListener() with the class that implements the ItemListener interface as the
parameter. The addItemListener() method is implemented by the Checkbox,
CheckboxMenuItem, Choice, and List components.

itemStateChanged(ItemEvent e)

The itemStateChanged() method is called when a component’s state is modified.


Every component is modified differently; for a List, modifying the component means
single-clicking on an entry. See the appropriate section for a description of each
component.

KeyListener and KeyAdapter


The KeyListener interface contains three methods that are called when a KeyEvent
occurs; key events are generated when the user presses or releases keys. The adapter class
for KeyListener is KeyAdapter. If you only care about one or two of the methods in
KeyListener, you can subclass the adapter and only override the methods that you are
interested in. For an object to listen for key events, it is necessary to call
Component.addKeyListener() with the class that implements the interface as the
parameter.

keyPressed(KeyEvent e)

The keyPressed() method is called when a user presses a key. A key press is, literally,
just what it says. A key press event is called for every key that is pressed, including keys
like Shift and Control. Therefore, a KEY_PRESSED event has a virtual key code
identifying the physical key that was pressed; but that’s not the same as a typed character,
which usually consists of several key presses. The keyTyped() method reports actual
characters.

keyReleased(KeyEvent e)

The keyReleased() method is called when a user releases a key. Like the keyPressed()
method, when dealing with keyReleased(), you must think of virtual key codes, not
characters.
keyTyped(KeyEvent e)

The keyTyped() method is called when a user types a key. The method keyTyped()
method reports the actual character typed. Action-oriented keys, like function keys, do
not trigger this method being called.

MouseListener and MouseAdapter

The MouseListener interface contains five methods that are called when a nonmotion
oriented MouseEvent occurs; mouse events are generated when the user presses or
releases a mouse button. (Separate classes, MouseMotionListener and
MouseMotionAdapter, are used to handle mouse motion events; this means that you can
listen for mouse clicks only, without being bothered by thousands of mouse motion
events.) The adapter class for MouseListener is MouseAdapter. If you care about only
one or two of the methods in MouseListener, you can subclass the adapter and override
only the methods that you are interested in. For an object to listen for mouse events, it is
necessary to call the method Window.addWindowListener() with the class that
implements the interface as the parameter.

mouseEntered(MouseEvent e)

The mouseEntered() method is called when the mouse first enters the bounding area of
the component.
mouseExited(MouseEvent e)

The mouseExited() method is called when the mouse leaves the bounding area of the
component.

mousePressed(MouseEvent e)

The mousePressed() method is called each time the user presses a mouse button within
the component’s space.

mouseReleased(MouseEvent e)

The mouseReleased() method is called when the user releases the mouse button after a
mouse press. The user does not have to be over the original component any more; the
original component is the source of the event.

mouseClicked(MouseEvent e)

The mouseClicked() method is called once each time the user clicks a mouse button; that
is, once for each mouse press/mouse release combination.

MouseMotionListener and MouseMotionAdapter


The MouseMotionListener interface contains two methods that are called when a motion-
oriented MouseEvent occurs; mouse motion events are generated when the user moves
the mouse, whether or not a button is pressed. MouseMotionAdapter is the adapter class
for MouseMotionListener. If you care about only one of the methods in
MouseMotionListener, you can subclass the adapter and override only the method that
you are interested in. For an object to listen for mouse motion events, it is necessar y to
call Component.addMouseMotionListener() with the class that implements the interface
as the parameter.

mouseMoved(MouseEvent e)
- The mouseMoved() method is called every time the mouse moves within
the bounding area of the component, and no mouse button is pressed.

mouseDragged(MouseEvent e)
- The mouseDragged() method is called every time the mouse moves
while a mouse button is pressed. The source of the MouseEvent is
the component that was under the mouse when it was first pressed.

TextListener

The TextListener interface contains the one method that is called when a TextEvent
occurs. It has no adapter class. For an object to listen for a TextEvent, it is necessar y to
call addTextListener() with the class that implements the TextListener interface as the
parameter. The addTextListener() method is implemented by the TextComponent class,
and thus the TextField and TextArea components.

textValueChanged(TextEvent e)
- The textValueChanged() method is called when a text component’s
contents are modified, either by the user or programmatically.

WindowListener and WindowAdapter

The WindowListener interface contains seven methods that are called when a
WindowEvent occurs; window events are generated when something changes the
visibility or status of a window. The adapter class for WindowListener is
WindowAdapter.

If you care about only one or two of the methods in WindowListener, you can subclass
the adapter and override only the methods that you are interested in. For an object to
listen for window events, it is necessary to call the method Window.
addWindowListener() or Dialog.addWindowListener() with the class that implements the
interface as the parameter.

windowOpened(WindowEvent e)
- The windowOpened() method is called when a Window is first
opened.
-
windowClosing(WindowEvent e)
- The windowClosing() method is triggered whenever the user tries to
close the Window.

windowClosed(WindowEvent e)
- The windowClosed() method is called after the Window has been closed.

windowIconified(WindowEvent e)
- The windowIconified() method is called whenever a user iconifies a
Window.

windowDeiconified(WindowEvent e)
- The windowDeiconified() method is called when the user deiconifies the
Window.

windowActivated(WindowEvent e)
- The windowActivated() method is called whenever a Window is brought
to the front.

windowDeactivated(WindowEvent e)
- The windowDeactivated() method is called when the Window is sent
away from the front, either through iconification, closing, or
another window becoming active.

Working with Delegation Event Model

Now that you have learned the theory behind the delegation event model and have had an
overview of its various components, it is time to see with an example. Here, we
implement and see some of the EventListener interface in details.

Handling Action Event

To handle Action event, you must implement the ActionListener interface into your
program. Let’s see an example for this,

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ActionEx extends Applet implements ActionListener
{
String s="";
Button r, g, b;
int c1,c2,c3;
public void init()
{
r=new Button("Red");
g=new Button("Green");
b=new Button("Blue");
add(r);
add(g);
add(b);
r.addActionListener(this);
g.addActionListener(this);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Red"))
{
c1=255;
c2=0;
c3=0;
}
else if(str.equals("Green"))
{
c1=0;
c2=255;
c3=0;
}
else
{
c1=0;
c2=0;
c3=255;
}
repaint();
}
public void paint(Graphics g)
{
Color c=new Color(c1,c2,c3);
setBackground(c);
}
}
/*
<applet code="ActionEx" width=250 height=150>
</applet>
*/

While compiling and running this program the output will be,

From the example, you can see that when the button is clicked the ActionEvent is called
and corresponding action his performed. Here, when you click red the background of the
applet become red, likewise while you click button green it become green and while blue
is become blue as show in the output screen.

Handling Mouse Events


To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces. Let’s see an example for this,

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseEx extends Applet implements MouseListener, MouseMotionListener
{
String msg="";
String s="";
int X=0, Y=0, R=0, G=0, B=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "Mouse clicked.";
R=0;
G=0;
B=255;
repaint();
}
public void mouseEntered(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "Mouse Entered.";
R=255;
G=0;
B=0;
repaint();
}
public void mouseExited(MouseEvent me)
{}
public void mousePressed(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "Down";
R=0;
G=255;
B=0;
repaint();
}
public void mouseReleased(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "Up";
R=255;
G=0;
B=0;
repaint();
}
public void mouseDragged(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "Dragged";
R=0;
G=255;
B=0;
repaint();
}
public void mouseMoved(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "Moved";
R=255;
G=0;
B=0;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 120, 10);
Color c = new Color(R,G,B);
g.setColor(c);
g.fillOval(X,Y,20,20);
}
}
/*
<applet code="MouseEx" width=300 height=100>
</applet>
*/

While compiling and running this program the output will be,
From this example, you can see that according to different mouse movement the circle
gets changed and moved with the mouse cursor.

Handling Keyboard Events

To handle keyboard events, you have to implementing the KeyListener interface. Let’s
see an example for this,

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyBoardEx extends Applet implements KeyListener
{
String s1="Your Pressed:",s2="";
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
s2=""+ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(s1,90,50);
g.drawString(s2,170,50);
}
}
/*
<applet code="KeyBoardEx" width=300 height=100>
</applet>
*/

While compiling and running this program the output will be,

From this example, you can see that when any key is pressed by you, that will be drawn
in the applet using the drawString( ) method and the status of the key also show in the
status bar of the appletviewer.

Handling Item events

To handle the Item events you have to implements the ItemListener interface. Let’s see
an example for this,

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ItemEx extends Applet implements ItemListener
{
String s="";
Checkbox c1, c2, c3;
CheckboxGroup cbg;
public void init()
{
cbg=new CheckboxGroup();
c1=new Checkbox("Apple", cbg, true);
c2=new Checkbox("Orange", cbg, false);
c3=new Checkbox("Graphs", cbg, false);
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
s="Selected: ";
s+=cbg.getSelectedCheckbox().getLabel();
g.drawString(s, 70, 100);
}
}
/*
<applet code="ItemEx" width=250 height=150>
</applet>
*/

While compiling and running this program the output will be,

From the example, you can see that the ItemEvent is class when particular option is
selected and the selected item is drawn in the applet.

Você também pode gostar