0% found this document useful (0 votes)
0 views

Unit IV Java1

Uploaded by

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

Unit IV Java1

Uploaded by

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

IT T45- Java Programming

Unit: IV
Events, Event sources, Event classes, Event Listeners, Delegation event model, handling mouse and
keyboard events, Adapter classes.AWT : Concepts of components, container, panel, window, frame,
canvas, Font class, Color class and Graphics. Applets - Concepts of Applets, differences between
applets and applications, life cycle of an applet, types of applets, creating applets, passing parameters to
applets.

4.1 Events in Java

An event in Java is an object that is created when something changes within a graphical user
interface. If a user clicks on a button, clicks on a combo box, or types characters into a text field,
etc., then an event triggers, creating the relevant event object.

Event handling in Java is comprised of three key elements:


 Event source-which is an object that is created when an event occurs.
 Event listener-the object that "listens" for events and processes them when they occur.
 Event Object- Created when an event occurs (i.e., user interacts with a GUI component). It
contains all necessary information about the event that has occurred such as:
 Type of event that has occurred
 Source of the event
It is represented by an Event class.

Fig 4.1 Java Event Model

Any number of event listener objects can listen for all kinds of events from any number of event
source objects. For example, a program might create one listener per event source. Or a program might
have a single listener for all events from all sources. A program can even have more than one listener
for a single kind of event from a single event source.

4.2 Event Sources


A source is an object that generates an event. This occurs when object changes in some way.
Source may generate more than one type of event. A source must register listeners in order for the
listeners to receive notifications about a specific type of event. Each type of event has its own
registration method.
General form:
public void addTypeListener (TypeListener el)

When an event occurs, all registered listeners are notified and receive a copy of the event object.It is
called Multicasting the event.Some sources may allow only one listener to register.

SMVEC-Department of Information Technology Page 1


IT T45- Java Programming

General form:

public void addTypeListener (TypeListener el) throws java.util.TooManyListenersException

To remove the Listener:

public void removeTypeListener (TypeListener el)

4.2.1 Event Listener Registers to Event Source


A listener should be registered with a source .Once registered, listener waits until an event occurs
When an event occurs
 An event object created by the event source
 Event object is fired by the event source to the registered listeners (method of event listener is
called with an event object as a parameter)
Once the listener receives an event object from the source
 Deciphers the event
 Processes the event that occurred

4.3 Event Classes


At root of Java event class hierarchy is EventObject, which is in java.util.
EventObject (Object src) it Contains two methods:

 Object getSource()
 String toString()

AWTEvent class defined in java.awt package is a subclass of EventObject. It is superclass


(directly or indirectly) of all AWT-based events handled by delegation model. Method getID () can be
used to determine the type of event.

4.3.1 Main Event Classes in java.awt.event


Event Class Description

ActionEvent Generated when a button is pressed, a list is double-clicked, or a menu item is


selected
AdjustmentEvent Generated when a scroll bar is manipulated.

ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible.

ContainerEvent Generated when a component is added to or removed from a container.

FocusEvent Generated when a component gains or loses keyboard focus.

InputEvent Abstract super class for all component input event classes.

ItemEvent Generated when a check box or a list item is clicked; also occurs when a choice
selection is made or a checkable menu is selected or deselected.

KeyEvent Generated when input is received from the keyboard.

SMVEC-Department of Information Technology Page 2


IT T45- Java Programming

MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
TextEvent Generated when the value of a textarea or textfield is changed.

WindowEvent Generated when a window os activated, closed, deactivated, deiconified,


iconified, opened, or quit.

Sources of Events

 Button
 Checkbox
 Choice
 List
 Menu Item
 Scrollbar
 Text Components
 Window

4.3.1.1 ActionEvent Class:

The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event:
 ALT_MASK,
 CTRL_MASK,
 META_MASK,
 SHIFT_MASK.
There is integer constant ACTION_PERFORMED which can be used to identify action events.
ActionEvent has three constructors:
 ActionEvent (Object src, int type, String cmd)
 ActionEvent (Object src, int type, String cmd, int modifiers)
 ActionEvent (Object src, int type, String cmd, long when, int modifiers)

src - reference to the object that generated this event.


type- type of the event
cmd- command string of type of event
modifiers - modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was
generated.

Methods of ActionEvent Class:


getActionCommand( ) – method used by Command name for invoking ActionEvent object
String getActionCommand( )

getModifier( ) - method returns a value that indicates which modifier keys were pressed when the
event was generated.
int getModifier( )

getWhen( ) - method returns the time at which event took palce.


long getWhen()

SMVEC-Department of Information Technology Page 3


IT T45- Java Programming

4.3.1.2 The AdjustmentEvent Class:

There are five types of AdjustmentEvent. The AdjustmentEvent class defines integer constants
that can be used to identify them.
BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT The user clicked inside the scroll bar to increase its value.
TRACK The slider was dragged.
UINT_DECREMENT The button at the end of scroll bar was clicked to decrease its value.

UNIT_INCREMENT The button at the end of scroll bar was clicked to increase its value.

In addition there is an integer constant, ADJUSTMENT_VALUE_CHANGED that indicates


that a change has occurred.

AdjustmentEvent has a constructors:

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

src - reference to the object that generated this event.


type-type of the adjustment is specified by type
data- The types associated data is data.

Methods of AdjustmentEvent Class:

getAdjustable( )- method returns object that generated the event.


Adjustable get Adjustable()
For example, when a button is pressed, an action event is generated that has a command name equal to
the label on that button.

getAdjustmentType( ) - method returns the type of adjustment event.


int getAdjustmentType( )
getValue( ) method returns the amount of adjustment.
long getValue( )

4.3.1.3 The ComponentEvent Class:


There are four types of AdjustmentEvent. The AdjustmentEvent class defines integer constants that can
be used to identify them.

COMPONENT_HIDDEN The component was hidden.


COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.

ComponentEvent has a constructors:


ComponentEvent (Component src, int type)

SMVEC-Department of Information Technology Page 4


IT T45- Java Programming

 src - reference to the object that generated this event.


 type- The type of the adjustment is specified by type.

The ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent,


KeyEvent, MouseEvent, and WindowEvent.

The getComponent( ) method returns the component that generated the event.
Component getComponent ( )

4.3.1.4 The ContainerEvent Class:


There are two types of container events. The ContainerEvent class defines int constants that can
be used to identify them: COMPONENT_ADDEDand COMPONENT_REMOVED. They indicate
that a component has been added to or removed from the container.

ContainerEvent is a subclass of ComponentEvent and has a constructor:

ContainerEvent (Component src, int type, Component comp)

src -reference to the object that generated this event.


type- type of the event is specified
component -that has been added to or removed from the container class.

Methods of ContainerEvent Class

getContainer( ) - method returns a reference to the container that generated the event.
Container getContainer ( )
getChild( ) - method returns a reference to the component that was added to or removed from the
container.
Component getChild( )
4.3.1.5 The FocusEvent Class:
FocusEvents are identified by integer constants FOCUS_GAINED and FOCUS_LOST.

FocusEvent is a subclass of ComponentEvent and has these constructor:


 FocusEvent (Component src, int type)
 FocusEvent (Component src, int type, boolean temporaryFlag)
 FocusEvent (Component src, int type, boolean temporaryFlag, Component other)

 src -reference to the object that generated this event.


 type- The type of the event is specified .
 temporaryFlag - is set to true if the focus event is temporary. Otherwise it is set to false.
 other -component involved in the focus change, called the opposite component, is passed here.
Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost
focus.

Methods of FocusEvent Class:

getOppositeComponent( )- method used to determine the other component.


Component getOppositeComponent ( )

SMVEC-Department of Information Technology Page 5


IT T45- Java Programming

isTemporary( ) - method indicates that if this focus change is temporary.


boolean isTemporary()
The method returns true if the change is temporary.

4.3.1.6 The InputEvent Class:

The abstract class InputEvents is a subclass of ComponentEvent and is a superclass for


component input events. Its subclasses are KeyEvent and MouseEvent.

InputEvent defines several integer constants that represent any modifiers, such as the control
key being pressed, that might be associated with the event. The following eight modifiers are defined:

ALT_MASK BUTTON2_MASK META_MASK


ALT_GRAPH_MASK BUTTON3_MASK SHIFT_MASK
BUTTON1_MASK CTRL_MASK

However, because of possible conflict between the modifiers used by keyboard events and
mouse events, and other issues, the following extended modifier values were added:

ALT_DOWN_MASK BUTTON2_DOWN _MASK META_DOWN _MASK


ALT_GRAPH_DOWN _MASK BUTTON3_DOWN _MASK SHIFT_DOWN _MASK
BUTTON1_DOWN _MASK CTRL_DOWN _MASK

To test if a modifier was pressed at the time an event is generated.The forms of these methods
are shown below:

 boolean isAltDown()
 boolean isAltGraphDown()
 boolean isControlDown()
 boolean isMetaDown()
 boolean isShiftDown()

Methods of InputEvent Class:

getModifier( ) - method is used to obtain a value that contains all of the original modifier flags.
int getModifiers( )

getModifierEx( ) - method is used to obtain the extended modifiers.


int getModifiersEx( )

4.3.1.7 The ItemEvent Class:

There are two types of item events which are identified by two integer constants:

DESELECTED The user deselected an item.


SELECTED The user selected an item.

SMVEC-Department of Information Technology Page 6


IT T45- Java Programming

ItemEvent defiens one integer constant, ITEM_STATE_CHANGED that signifies a change of state.

ItemEvent uses the constructor:


ItemEvent (ItemSelectable src, int type, Object entry, int state)

 src - reference to the object that generated this event.


 type- The type of the event is specified
 entry- The specific item that generated the item event is passed here.
 state - current state of that item.

Methods of ItemEvent Class:

getItem( )- method returns a reference to the item that generated an event.


Object getItem ( )

getItemSelectable( ) - method returns a reference to the ItemSelectable object that generated an event.
ItemSelectable getItemSelectable ( )

getStateChange( )- method returns the state change(i.e, SELECTED or DESELECTED) for an event:
int getStateChange ( )

4.3.1.8 The KeyEvent Class:

There are three types of key events, which are identified by these integer
constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are
generated when a key is pressed or released. The last event occurs when a character is generated.

Many other integer constants that are defined by KeyEvent:

VK_ALT VK_DOWN VK_LEFT VK_RIGHT


VK_CANCLE VK_ENTER VK_ PAGE_DOWN VK_SHIFT
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP

The VK- constants specifies virtual key codes.

KeyEvent is a subclass of InputEvent and uses the constructor:

KeyEvent (Component src, int type, long when, int modifiers, int code, char ch)

 src -reference to the object that generated this event.


 type- type of the event is specified by type.
 when -The system time at which the key is pressed is passed in.
 modifier- argument specifies which modifiers were pressed when this key event occurred.
 code -The virtual key code is passed in.

The character equivalent is passed in ch. If no valid character exist, then ch contains
CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.

SMVEC-Department of Information Technology Page 7


IT T45- Java Programming

Methods of KeyEvent Class:


getKeyChar( )- method returns the character that was entered
char getKeyChar ( )

getKeyCode( ) -method returns the key code.


int getKeyCode ( )

4.3.1.9 The MouseEvent Class:

There are eigth types of mouse events. MouseEvent class defines the following integer constants:

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.
MOUSE_WHEEL The mouse wheel was moved.

MouseEvent class is a subclass of InputEvent. It uses the constructor:

MouseEvent (Component src, int type, long when, int modifier, int x,int y, int clicks, boolean
triggersPopup)

 src - reference to the object that generated this event.


 type- The type of the event is specified by type.
 when -The system time at which the mouse event occurred is passed in.
 modifier - argument specifies which modifiers were pressed when this mouse event occurred.
 int x, int y -The coordinates of the mouse are passed in x and y.
 clicks -click count is passed in .
 triggerPopup- flag indicates if this event causes a popup menu to appear on this platform.

Methods of MouseEvent Class:


getX( ) and getY( ) - methods returns the x and y coordinates of the mouse within the component when
the event occurred.
int getX( )
int getY( )

getPoint( ) - method is used to obtain the coordinates of the mouse:


Point getPoint( )

translatePoint( ) -method changes the location of the event.


void translatePoint (int x, int y)
Here, the arguments x and y are added to the coordinates of the event.

getClickCount( )- method returns the number of mouse clicks for an event:


int getClickCount ( )

SMVEC-Department of Information Technology Page 8


IT T45- Java Programming

isPopupTrigger( ) - method tests if this event causes a pop-up menu to appear on this platform.
boolean isPopupTrigger( )

getButton( )- method that represent the button that caused the event:
int getButton( )

NOBUTTON BUTTON1 BUTTON2 BUTTON3

NOBUTTON indicates that no button was pressed or released.

4.3.1.10 The MouseWheelEvent Class:

MouseWheelEvent is a subclass of MouseEvent. Mouse wheels are used for scrolling.


MouseWheelEvent defines two integer constants:

WHEEL_BLOCK_SCROLL A page-up or page-down scroll event occurred.

WHEEL_UNIT_SCROLL A line-up or line-down scroll event occurred.

MouseWheelEvent uses the constructor:

MouseWheelEvent (Component src, int type, long when, int modifier, int x,int y, int clicks, boolean
triggersPopup, int scrollHow, int amont, int count)

 src -reference to the object that generated this event.


 type- type of the event is specified by type.
 when -The system time at which the mouse event occurred is passed in.
 modifier -argument specifies which modifiers were pressed when this mouse event occurred.
 int x,int y- The coordinates of the mouse are passed in x and y.
 clicks-The number of clicks the wheel has rotated is passed in
 triggerPopup- flag indicates if this event causes a popup menu to appear on this platform.
 scrollHow - value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
 amount- The number of units to scroll is passed in
 count- parameter indicates the number of rotational units that the wheel moved.

Methods of MouseWheelEvent Class:

getWheelEvent( ) - method returns number of rotational units:


int getWheelRotation( )
A positive value is returned if the wheel moved counterclockwise. The negative value is returned if the
wheel moved clockwise.

getScrollType() -methodreturns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.


int getScrollType ( )
If WHEEL_UNIT_SCROLL is returned getScrollAmount() can be called to obtain the number of
units scrolled:
int getScrollAmount( )

SMVEC-Department of Information Technology Page 9


IT T45- Java Programming

4.3.1.11 The TextEvent Class:

TextEvents are defines the integer constant TEXT_VALUE_CHANGED.


TextEvent has the constructor:
TextEvent (Object src, int type)
 src - reference to the object that generated this event.
 type-The type of the event is specified by type.

The text event object does not include the characters currently in the text components that generated the
event.

4.3.1.12 The WindowEvent Class:


WindowEvent class defines the following integer constants that can be used to identify them:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_ DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.

WindowEvent class is a subclass of ComponentEvent. It uses the constructor:


 WindowEvent (Window src, int type)
 WindowEvent (Window src, int type, Window other)
 WindowEvent (Window src, int type, int fromState, int toState)
 WindowEvent (Window src, int type, Window other, int fromState, int toState)

 src -reference to the object that generated this event.


 type- The type of the event is specified by type.
 other- specifies the opposite window when a focus or activation event occurs.
 fromState- specifies the prior state of the window,
 toState- specifies the next state of the window.

getWindow( ) - method returns the object that generated the event.


Window getWindow( )

WindowEvent also defines methods that returns the opposite window (When a focus or activation event
has occurred), the previous window state and the current window state:
Window getOppositeWindow()
int getOldState()
int getNewState()

SMVEC-Department of Information Technology Page 10


IT T45- Java Programming

4.3.2 Sources of Events

Source Actual event Event type


Button Button pressed Action event
Checkbox Item Selected or deselected Item event
Choice Choice changed Item event
List Item double clicked Action event
Item selected or deselected Item event
Menu Item Item selected Action event
Checkable menu item isselected or deselected Item event
Scroll bar Scroll bar manipulated Adjustment event
Text components Character entered Text event
Window Window opened, closed or activated Window events

4.4 Event Listeners

 The delegation event model has two parts : sources and listeners
 Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package. When an event occurs, the event source invokes the appropriate
method defined by the listener and provides an event object as its argument.

The commonly used listener interfaces are:

SMVEC-Department of Information Technology Page 11


IT T45- Java Programming

4.4.1 The ActionListener Interface:


The ActionListener interface defines actionPerformed()method that is invoked when an action
event occurs.
void actionPerformed(ActionEvent ae)

4.4.2 The AdjustmentListener Interface:


This interface defines the adjustmentValueChanged()method that is invoked when an
adjustment event occurs.
void adjustmentValueChanged(AdjustmentEvent ae)

4.4.3 The ComponentListener Interface:


This interface defines four methods that are invoked when a component is resized, moved,
shown or hidden.
 void componentResized(ComponentEvent ce)
 void componentMoved(ComponentEvent ce)
 void componentShown(ComponentEvent ce)
 void componentHidden(ComponentEvent ce)

4.4.4 The ContainerListener Interface:


This interface defines two methods that are invoked when a component is added to or removed
from a container.
 void componentAdded(ContainerEvent ce)
 void componentRemoved(ContainerEvent ce)

4.4.5 The FocusListener Interface:


This interface defines two methods that are invoked when a component ontains or loses
keyboard focus.
 void focusGained(FocusEvent fe)
 void focusLost(FocusEvent fe)

4.4.6 The ItemListener Interface:


This interface defines the itemStateChanged()methods that is invoked when the state of an
item changes.
void itemStateChanged(ItemEvent ie)

4.4.7 The KeyListener Interface:


This interface defines three methods that are invoked when a key is pressed, released or when a
character has been entered.
 void keyPressed(KeyEvent ke)
 void KeyReleased(KeyEvent ke)
 void KeyTyped(KeyEvent ke)

4.4.8 The MouseListener Interface:


This interface defines five methods. If the mouse is pressed or released at the same
point, mouseClicked() is invoked. When the mouse enters a component, the mouseEntered()event is
called. When it leaves mouseExited()method is called.
The mousePressed()and mouseReleased() methods are invoked when the mouse is pressed or
released, respectively.

SMVEC-Department of Information Technology Page 12


IT T45- Java Programming

 void mouseClicked(MouseEvent me)


 void mouseEntered(MouseEvent me)
 void mouseExited(MouseEvent me)
 void mousePressed(MouseEvent me)
 void mouseReleased(MouseEvent me)

4.4.9 The MouseMotionListener Interface:


This interface defines two methods. The mouseDragged()method is called multiple times as
the mouse is dragged. The mouseMoved() method is called multiple times as the mouse is moved.
 void mouseDragged(MouseEvent me)
 void mouseMoved(MouseEvent me)

4.4.10 The MouseWheelListener Interface:


This interface defines mouseWheelMoved()method that is called when the mouse wheel is
moved.
void mouseWheelMoved(MouseWheelEvent mwe)

4.4.11 The TextListener Interface:


This interface defines textChanged()method that is called when a change occurs in a text area
or text field.
void textChanged(TextEvent te)

4.4.12 The WindowFocusListener Interface:


This interface defines two methods that are called when a window gains or loses input focus.
 void windowGainedFocus(WindowEvent we)
 void windowLostFocus(WindowEvent we)

4.4.13 The WindowListener Interface:


This interface defines seven methods.

 The windowActivated()and windowDeactivated() methods are invoked when a window is


activated or deactivated, respectively.
 If a window is iconified, the windowIconified()method is called.
 When a window is deiconified, the windowDeiconified() method is called.
 When a window is opened or closed, the windowOpened() or windowClosed() method is
called. When the window is being closed the windowClosing()method is called.

 void windowActivated(WindowEvent we)


 void windowClosed(WindowEvent we)
 void windowClosing(WindowEvent we)
 void windowDeactivated(WindowEvent we)
 void windowDeiconified(WindowEvent we)
 void windowIconified(WindowEvent we)
 void windowOpened(WindowEvent we)

SMVEC-Department of Information Technology Page 13


IT T45- Java Programming

4.5 Delegation Event Model


The Fig 4.2 event model is also called the "delegation" event model because event handling is
delegated to different objects and methods .The idea is that events are processed by event listeners,
which are separate objects that handle specific types of events.
Following are the basic steps in using delegation event model or for handling events in a Java program:
 Implement the appropriate listener interface.
 Register the listener with the source.
 Provide appropriate event handler to handle the event raised on the source

Fig 4.2 Event Delegation Model

In the delegation event model, a class designated as an event source generates an event and sends it to
one or more listeners. The responsibility of handling the event process is handed over to its listeners.
However, the listeners must register or agree with the event source class to receive any notification.
This means that a particular event is processed only by a specific listener.

 The listener registers and specifies which events are of interest (for instance mouse events).
 Only those events that are being listened for will be processed.
 Each different event type uses a separate Event class.
 Each different kind of listener also uses a separate class.
 This model makes event handling more efficient because not all events have to be processed
and the events that are processed are only sent to the registered listeners rather than to an entire
hierarchy of event handlers.
 Also, using different event classes allows the Java compiler to perform more specific type error
checking.

4.5.1 Handling Mouse Events:

Listeners are created by using one or more of the interfaces defined by the java.awt.event package.

Example: MyEventApplet.Java

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

SMVEC-Department of Information Technology Page 14


IT T45- Java Programming

public class MyEventApplet extends Applet implements MouseListener, MouseMotionListener


{
String msg=‖‖;
int x,y;
public void init()
{
x=y=0;
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
public void mouseClicked(MouseEvent e)
{
x=e.getX();
y=e.getY();
msg=‖Mouse Clicked‖;
}
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
msg=‖Mouse Pressed‖;
}
public void mouseReleased(MouseEvent e)
{
x=e.getX();
y=e.getY();
msg=‖Mouse Released‖;
}
public void mouseMoved(MouseEvent e)
{
x=e.getX();
y=e.getY();
showStatus(―Mouse Moved at ―+x+‖ , ―+y);
repaint( );
}
public void mouseDragged(MouseEvent e)
{
x=e.getX();
y=e.getY();
showStatus(―Mouse Dragged at ―+x+‖ , ―+y);
repaint();
}
public void mouseExited(MouseEvent e)
{
x=0;
y=10;
SMVEC-Department of Information Technology Page 15
IT T45- Java Programming

msg=‖Mouse exited‖;
repaint();
}
public void mouseEntered(MouseEvent e)
{
x=0;
y=10;
msg=‖Mouse exited‖;
}
}

4.5.2 Handling Keyboard Events:

Listeners are created by using one or more of the interfaces defined by the java.awt.event package.
Example:MyKeyApplet.java
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
public class MyKeyApplet extends Applet implements KeyListener
{
String msg=‖‖;
int x=10,y=40;
public void init()
{
addKeyListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
public void keyPressed(KeyEvent e)
{
int keycode=e.getKeyCode();
switch(keycode)
{

case KeyEvent.VK_PAGE_UP:
msg+=‖ Page UP ―;
break;
case KeyEvent.VK_LEFT:
msg+=‖ Left Arrow ―;
break;
}
repaint( );
}
public void keyTyped(KeyEvent e)
{
msg+=e.getKeyChar();
repaint( );
}
SMVEC-Department of Information Technology Page 16
IT T45- Java Programming

public void keyReleased(KeyEvent e)


{
msg+=‖Key Released‖;
repaint();
}
}

In the above example, whenever a keyboard button is pressed, appropriate message is displayed on the
applet screen. With the help of appropriate listener the various event generated through keyboard can
be handled.

4.6 Adapter Class

Need of abstract class:


Implementing all methods of an interface takes a lot of work. Interested in implementing some
methods of the interface only

Adapter classes:
They are built-in in Java class which implement all methods of each listener interface with
more than one method. Implementations of the methods are all empty. They are useful when we want
to listen and process only some of the events that are handled by one particular event listener interface.

We can define your own class as subclass of this class and provide desired implementation. The
Listener Interfaces implemented by Adapter classes

Adapter Class Listener Interface

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

FocusAdapter FocusListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

WindowAdapter WindowListener

Example:AdapterDemo.java

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

/*<applet code="AdapterDemo" width=300 height=100> </applet>*/

SMVEC-Department of Information Technology Page 17


IT T45- Java Programming

public class AdapterDemo extends Applet


{
public void init ( )
{
addMouseListener(new MyMouseAdapter (this));
addMouseMotionListener(new MyMouseMotionAdapter (this));
}
}

class MyMouseAdapter extends MouseAdapter


{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked
public void mouseClicked (MouseEvent me)
{
adapterDemo.showStatus ("Mouse Clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter (AdapterDemo adapterDemo)
{
this. adapterDemo = adapterDemo;
}
// Handle Mouse Drag
public void mouseDragged (MouseEvent me)
{
adapterDemo.showStatus("Mouse Dragged");
}
}

4.7 AWT : Concepts of components

AWT (Abstract Window Toolkit) was Java’s first GUI framework, which was introduced in
Java 1.0. It is used to create GUIs (Graphical User Interfaces). Java AWT components are platform-
dependent i.e. components are displayed according to the view of operating system. AWT is
heavyweight i.e. its components are using the resources of OS. For example if you are instantiating a
text box in AWT that means you are actually asking OS to create a text box for you.

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc. The Abstract Window Toolkit (AWT) supports Graphical
User Interface (GUI) programming.

SMVEC-Department of Information Technology Page 18


IT T45- Java Programming

AWT features :
 A set of native user interface components. A robust event-handling model

 Graphics and imaging tools, including shape, color, and font classes

 Layout managers, for flexible window layouts that do not depend on a particular window size or
screen resolution

 Data transfer classes, for cut-and-paste through the native platform clipboard

4.7.1 Java AWT Hierarchy


Component: A Component is an abstract super class for GUI controls and it represents an object with
graphical representation.

Fig 4.3 Hierarchy of Java AWT classes

Component class
Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible for remembering
the current foreground and background colors and the currently selected text font.
Container
Container is a component in AWT that contains another component like button, text field,
tables etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.

SMVEC-Department of Information Technology Page 19


IT T45- Java Programming

Panel

Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
border. It is container that is used for holding components. 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.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class EventL extends Applet implements ActionListener


{

Panel p1;
Button b,c;
Image backGround;

public void init()


{
backGround = getImage(getCodeBase(), "Autumn.jpg");

Panel p1 = new Panel();

b = new Button("Autumn");
c = new Button("Winter");

p1.add(b);
p1.add(c);

setLayout(new GridLayout(10,1));
add(p1);

b.addActionListener(this);
c.addActionListener(this);

}
public void paint(Graphics g)
{
g.drawImage(backGround,0,100,this);
}
SMVEC-Department of Information Technology Page 20
IT T45- Java Programming

public void actionPerformed(ActionEvent e)


{
if(e.getSource()== b)
{
backGround = getImage(getDocumentBase(), "image1.jpg");
}
else
{
backGround = getImage(getDocumentBase(), "image2.jpg");
}
repaint();
}

/*<applet code="EventL.class" height="500" width="500"> </applet>*/

Window class
Window class creates a top level window. Window does not have borders and menubar. It uses Border
Layout as default layout manager.

Class declaration:

Following is the declaration for java.awt.Window class:

public class Window


extends Container
implements Accessible

Class constructors

S.N. Constructor & Description


Window(Frame owner)
1
Constructs a new, initially invisible window with the specified Frame as its owner.
Window(Window owner)
2
Constructs a new, initially invisible window with the specified Window as its owner.
Window(Window owner, GraphicsConfiguration gc)
3
Constructs a new, initially invisible window with the specified owner Window and a
GraphicsConfiguration of a screen device.

SMVEC-Department of Information Technology Page 21


IT T45- Java Programming

Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT applications
are created using Frame window. Frame class has two different constructors,

 Frame( ) throws HeadlessException


 Frame(String title) throws HeadlessException

Creating a Frame
There are two ways to create a Frame. They are,
 By Instantiating Frame class
 By extending Frame class
import java.awt.*;

public class MyApp extends Frame


{
// "final" variables are constants
static final int H_SIZE = 300;
static final int V_SIZE = 200;

public MyApp()
{
// Calls the parent constructor
// Frame(string title)
// Equivalent to setTitle("My First Application")
super("My First Application");

pack();
resize(H_SIZE, V_SIZE);
show();
}

public static void main(String args[])


{
new MyApp();
}
}
The class above Is-A Frame, since it extends(i.e inherits) from it. It has one method, the constructor
takes no parameters, we made an explicit call to the super constructor(i.e parent constructor) if we did
not Java would call the constructor anyways. But we decided to utilize the parent constructor and pass
it a string which is the title of our application.

show()- is required because by default, AWT Containers are created hidden and must be made visible.
Pack()- is used here to properly adjust Components such as Buttons, Lists, etc. to their correct sizes.

Note: static void main(String args[]) is considered a class method, not an instance method. It really
does not depend on an instance of MyApp and does not belong to it.
SMVEC-Department of Information Technology Page 22
IT T45- Java Programming

It has the following attributes:

 300 x 200 Frame


 No menubar
 No Components
 Title bar with "My first Application"
 Default colored background
 Default layout
 Blank background

import java.io.*;

import java.awt.*;

import java.awt.event.*;

public class AwtControl extends Frame implements ActionListener

Label l1, l2, l3, l4, l5, l6, l7;

TextField t1, t2, t3, t4;

Choice ch1;

Checkbox cb1, cb2;

CheckboxGroup cbg;

List It;

Button b1, b2;

Panel p1;

TextArea ta;
SMVEC-Department of Information Technology Page 23
IT T45- Java Programming

public AwtControl()

setLayout(new GridLayout(10, 2));

ta = new TextArea( 20, 20);

l1 = new Label("Student ID ");

l2 = new Label("Name ");

l3 = new Label("College");

l4 = new Label("Department");

l5 = new Label("Gender ");

l6 = new Label("Extra activities");

t1 = new TextField(20);

t2 = new TextField(20);

t3 = new TextField(20);

ch1 = new Choice();

ch1.addItem("CSE");

ch1.addItem("IT");

ch1.addItem("MCA");

ch1.addItem("ECE");

cbg = new CheckboxGroup();

cb1 = new Checkbox("Male", cbg, true);

cb2 = new Checkbox("Female", cbg, true);

p1 = new Panel();

SMVEC-Department of Information Technology Page 24


IT T45- Java Programming

p1.add(cb1);

p1.add(cb2);

It = new List();

It.addItem("Sports");

It.addItem("Graphics");

It.addItem("Mobile Technology");

b1 = new Button("Show");

b1.addActionListener(this);

b2 = new Button("Exit");

b2.addActionListener(this);

add(l1);

add(t1);

add(l2);

add(t2);

add(l3);

add(t3);

add(l4);

add(ch1);

add(l5);

add(p1);

add(l6);

add(It);

add(b1);

add(b2);

add(ta);

SMVEC-Department of Information Technology Page 25


IT T45- Java Programming

public void actionPerformed(ActionEvent e)

if(e.getSource()==b2)

System.exit(0);

ta.setText(""); //Clear

ta.append(t1.getText() + "\n");

ta.append(t2.getText()+ "\n");

ta.append(t3.getText()+ "\n");

ta.append(ch1.getSelectedItem()+ "\n");

ta.append(cbg.getSelectedCheckbox().getLabel()+ "\n");

ta.append(It.getSelectedItem()+ "\n");

public void windowClosing(WindowEvent e)

dispose();

System.exit(0);

public static void main(String args[])

AwtControl control = new AwtControl();

control.setSize(600,600);

control.setVisible(true);

SMVEC-Department of Information Technology Page 26


IT T45- Java Programming

Canvas
The Canvas control represents a blank rectangular area where the application can draw or trap
input events from the user. It inherits the Component class.

AWT Canvas class Declaration


public class Canvas extends Component implements Accessible

Constructor of the Canvas class are :

1. Canvas(): Creates a new blank canvas.


2. Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics
configuration.

Commonly used Methods in Canvas Class

Method Explanantion
addNotify() Creates the peer of the canvas.
createBufferStrategy(int n) Creates a new strategy for multi-buffering on this component.
createBufferStrategy(int n, Creates a new strategy for multi-buffering on this component
BufferCapabilities c) with the required buffer capabilities
getBufferStrategy() Returns the BufferStrategy used by this component.
paint(Graphics g) paints this component.
update(Graphics g) updates this canvas.

Font Class
The Font class provides a method of specifying and using fonts. The Font class constructor
constructs font objects using the font's name, style (PLAIN, BOLD, ITALIC, or BOLD + ITALIC), and
point size.
Java Font constructor:
Font class sets font to the text. The text may represent a string displayed by drawString( ),
setText( ), setLabel( ), appendText etc. methods.

Syntax of Font constructor to create a Font object

Font f1 = new Font(String fontName, int fontStyle, int fontSize);

To give the font style as an integer value, the Font class comes with three symbolic constants as
follows.
public final static int PLAIN = 0;
public final static int BOLD = 1;
public final static int ITALIC = 2;

Java supports 5 font names. They are


 Monospaced
 Serif
 Dialog

SMVEC-Department of Information Technology Page 27


IT T45- Java Programming

 SansSerif
 DialogInput

If any other font name is given, it is not an error or exception, but takes Dialog as the default (style:
plain and size: 12).

Example:

Font f1 = new Font("Monospaced", Font.BOLD, 15);


Font f2 = new Font("SansSerif", Font.ITALIC, 18);
Font f3 = new Font("Dialog", Font.BOLD + Font.ITALIC, 20);

Color Class
The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class
creates color by using the given RGBA values where RGBA stands for RED, GREEN, BLUE, ALPHA
or using HSB value where HSB stands for HUE, SATURATION, BRI components. The value for
individual components RGBA ranges from 0 to 255 or 0.0 to 0.1. The value of alpha determines the
opacity of the color, where 0 or 0.0 stands fully transparent and 255 or 1.0 stands opaque.

Constructors of Color Class

 Color(ColorSpace c, float[] co, float a) : Creates a color in the specified ColorSpace with the
color components specified in the float array and the specified alpha.

 Color(float r, float g, float b) : creates a opaque color with specified RGB components(values
are in range 0.0 – 0.1)

 Color(float r, float g, float b, float a) : creates a color with specified RGBA


components(values are in range 0.0 – 0.1)

 Color(int rgb): Creates an opaque RGB color with the specified combined RGB value
consisting of the red component in bits 16-23, the green component in bits 8 – 15, and the blue
component in bits 0-7.

 Color(int rgba, boolean b): Creates an sRGB color with the specified combined RGBA value
consisting of the alpha component in bits 24-31, the red component in bits 16 – 23, the green
component in bits 8
– 15, and the blue component in bits 0 – 7.

 Color(int r, int g, int b) : Creates a opaque color with specified RGB components(values are in
range 0 – 255)

 Color(int r, int g, int b, int a) : Creates a color with specified RGBA components(values are in
range 0 – 255)

SMVEC-Department of Information Technology Page 28


IT T45- Java Programming

Graphics Class

The Graphics class provides the framework for all graphics operations within the AWT. The Graphics
class is an abstract class that provides the means to access different graphics devices. It is the class that
lets you draw on the screen, display images, and so forth.
The graphics context is encapsulated by the Graphics class and is obtained in two ways:

• It is passed to a method, such as paint( ) or update( ), as an argument.

• It is returned by the getGraphics( ) method of Component.

repaint( )

• public void repaint()


• public void repaint(long tm)
• public void repaint(int x, int y, int w, int h)
• public void repaint(long tm, int x, int y, int w, int h)

The repaint() method requests that a component be repainted. The caller may request that repainting
occur as soon as possible, or may specify a period of time in milliseconds. If a period of time is
specified, the painting operation will occur before the period of time elapses. The caller may also
specify that only a portion of a component be repainted. This technique is useful if the paint operation
is time-consuming, and only a portion of the display needs repainting.

update( )

public void update(Graphics g)


The update( ) method is called in response to a repaint() request, or in response to a portion of the
component being uncovered or displayed for the first time.

paint( )

public void paint(Graphics g)


The paint( ) method is called from an update( ) method, and is responsible for actually drawing the
graphics. The method's only argument is an instance of the Graphics class.

Drawing Functions of Graphics Class:


The Graphics class defines a number of drawing functions.

Drawing Lines
Lines are drawn by means of the drawLine() method,shown here:

SMVEC-Department of Information Technology Page 29


IT T45- Java Programming

void drawLine(int startX,int startY,int endX,int endY)

import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet
{
int width, height;
public void init()
{
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}

public void paint( Graphics g )


{
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i )
{
g.drawLine( width, height, i * width / 10, 0 );
}
}
}

Sample output from this program is shown here:

SMVEC-Department of Information Technology Page 30


IT T45- Java Programming

Drawing Rectangles
The drawRect() and fillRect() methods display an outlined and filled rectangle, respectively.

Syntax:
void drawRect(int top,int left,int width,int height)
void fillRect(int top,int left,int width,int height)

The upper left corner of the rectangle is at top,left. The dimension of the rectangle are specified by the
width,height.To draw rounded rectangle,use drawRoundRect()or fillRoundRect().

Syntax:
void drawRoundRect(int top,int left,int width,int height,int xDiam,int yDiam)
void fillRoundRect(int top,int left,int width,int height,int xDiam,int yDiam)

A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at top,left. The
dimensions of the rectangle are specified by width and height.The diameter of the rounding arc along
the X axis is specified by Diam. The diameter of the rounding arc along the Y axis is specified by
yDiam. applet program to draws several rectangles:

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}
Sample output from this program is shown here:

SMVEC-Department of Information Technology Page 31


IT T45- Java Programming

Drawing Ellipses and Circles


To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ).
Syntax:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)

The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top,left and
whose width and height are specified by width and height. To draw a circle, specify a square as the
bounding rectangle.

The following program draws several ellipses:

// Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/

public class Ellipses extends Applet


{
public void paint(Graphics g)
{
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}

Sample output from this program is shown here:

SMVEC-Department of Information Technology Page 32


IT T45- Java Programming

Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:

void drawArc(int top, int left, int width, int height, intstartAngle,intsweepAngle)
void fillArc(int top, int left, int width, int height, intstartAngle,intsweepAngle)

The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose
width and height are specified by width and height. The arc is drawn from startAngle through the
angular distance specified by sweepAngle.
Angles are specified in degrees. Zero degrees is on the horizontal, at the three o’clock position.
The arc is drawn counterclockwise ifsweepAngle is positive, and clockwise if sweepAngle is negative.
Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle would be 90 and the sweep
angle 180.

The following applet draws several arcs:


import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 height=200>
</applet>*/
public class Arcs extends Applet
{
public void paint(Graphics g)
{
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}
Sample output from this program is shown here:

SMVEC-Department of Information Technology Page 33


IT T45- Java Programming

Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),
shown here:

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


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

The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The
number of points defined by x and y is specified by numPoints. There are alternative forms of these
methods in which the polygon is specified by a Polygon object.

The following applet draws an polygon

import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
{
public void paint(Graphics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}

Sample output from this program is shown here:

SMVEC-Department of Information Technology Page 34


IT T45- Java Programming

4.8 Applets - Concepts of Applets

4.8.1 Java Applet Basics


Applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. Applet is embedded in a HTML page using the APPLET or OBJECT tag and
hosted on a web server. Applets are used to make the web site more dynamic and entertaining.

 All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.


 Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.
 In general, execution of an applet does not begin at main() method.
 Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().

Advantage of Applet

It works at client side so less response time.


Secured
It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
Drawback of Applet

 Plug in is required at client browser to execute applet.


There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).

4.8.2 Differences between applets and applications


Applications are standalone Java programs that run on the underlying operating system. It is
designed to perform a specific task. They can run with or without the help of a Graphical User Interface
(GUI). These applications can be text processing programs, image processing programs, database
programs, etc.

SMVEC-Department of Information Technology Page 35


IT T45- Java Programming

Applet Application

A small Program that performs a specific task


A standalone program that is designed to run on
that run within a particular environment and need
a standalone machine to perform a task
a plug in.
Large Program
Small Program
Can be executed on stand alone computer
Used to run a program on client Browser
system
Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client
JAVA supported browser. machine.

Applet applications are executed in a Restricted Application can access all the resources of the
Environment. It cannot read and write the files computer. It can perform File reading and
form the local computer writing on the local computer
Applets are created by extending the Applications are created by writing public static
java.applet.Applet void main(String[] s) method.
Applet application has 5 methods which will be
Application has a single start point which is
automatically invoked on occurrence of specific
main method
event
Example:
import java.awt.*;
import java.applet.*;
public class Myclass extends Applet
public class MyClass
{
{
public void init() { }
public static void main(String args[]) {}
public void start() { }
}
public void stop() {}
public void destroy() {}
public void paint(Graphics g) {}
}

4.8.3 Life Cycle Of An Applet


Java applet inherits features from the class Applet. Thus, whenever an applet is created, it
undergoes a series of changes from initialization to destruction. Various stages of an applet life cycle
are depicted in the figure below:

SMVEC-Department of Information Technology Page 36


IT T45- Java Programming

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.When an applet begins, the following methods are called, in this sequence:

 init( )
 start( )
 paint( )

When an applet is terminated, the following sequence of method calls takes place:

 stop( )
 destroy( )

The following methods are available in the java.applet.Applet class and java.awt.Component
class(paint( ))

init( ) : The init( ) method is the first method to be called. This is where you should initialize variables.
This method is called only once during the run time of your applet.

public void init() {


//Action to be performed
}

start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped. Note that init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is
called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page
and comes back, the applet resumes execution at start( ).

public void start() {


//Action to be performed
}

paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is running may be
overwritten by another window and then uncovered. Or the applet window may be minimized and then
restored.

SMVEC-Department of Information Technology Page 37


IT T45- Java Programming

 paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
 The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.

void paint(Graphics g){


//Action to be performed
}

stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop( ) is called, the applet is probably
running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible.
You can restart them when start( ) is called if the user returns to the page.

public void stop() {


//Action to be performed
}

destroy( ) : The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory. At this point, you should free up any resources the applet may
be using. The stop( ) method is always called before destroy( ).

public void destroy() {


//Action to be performed
}
Example:
import java.awt.*;
/*<applet code="AppletLifeCycle.class" width="350" height="150"> </applet>*/
public class AppletLifeCycle extends Applet
{
public void init()
{
setBackground(Color.CYAN);
System.out.println("init() called");
}
public void start()
{
System.out.println("Start() called");

}
public void paint(Graphics g)
{
System.out.println("Paint(() called");
}

SMVEC-Department of Information Technology Page 38


IT T45- Java Programming

public void stop()


{
System.out.println("Stop() Called");
}
public void destroy()
{
System.out.println("Destroy)() Called");
}
}
Output:

init() called
Start() called
Paint(() called
Paint(() called
Stop() Called
Start() called
Paint(() called
Stop() Called
Destroy)() Called

4.8.4 Types of applets


Applet is java program that can be embedded into HTML pages. Java applets run on the java
enables web browsers such as Mozilla and internet explorer. They run as a part of web document.
Applet requires Java runtime Environment .Applet interact with user using AWT toolkit( Abstract
window Toolkit) .It provides the graphics user interface. It is secure because It do not access the user
system resources and do not do concept of file handling, that is why they do not contains any malicious
infection with them and hence do not harm the system. There are two type of applet in java.
 Local Applet
 Remote Applet

Local Applet:
When we create our own applet and store them to our local system then this type of applet is termed as
Local applet.So if a webpage want to access this applet it will only need to search directories of the
local system and no internet is required.
SMVEC-Department of Information Technology Page 39
IT T45- Java Programming

Specifying a Local Applet


<applet codebase="path" code="NewApplet.class" width=120 height=120 >
</apple>

In the above example, the codebase attribute specifies a path name on your system for the local applet,
whereas the code attribute specifies the name of the byte-code file that contains the applet's code. The
path specified in the codebase attribute is relative to the folder containing the HTML document that
references the applet.

Remote Applet:
A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet. we can download the remote applet on to our system via at the
internet and run it. In order to locate and load a remote applet, we must known the applets
address on the web. This address is known as uniform resource locator (URL).

Specifying a Remote Applet


<applet
codebase="http://www.myconnect.com/applets/" code="NewApplet.class" width=120 height=120 >
</applet>

The only difference between Local Applet and Remote Applet is the value of the codebase attribute. In
the first case, codebase specifies a local folder, and in the second case, it specifies the URL at which the
applet is located.
SMVEC-Department of Information Technology Page 40
IT T45- Java Programming

Features of Applets over HTML

 Displaying dynamic web pages of a web application.


 Playing sound files.
 Displaying documents
 Playing animations

4.9 Creating applets:


4.9.1 Creating an Example applet :
import java.awt.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.event.*;
public class Division extends Applet implements ActionListener
{
TextField t1,t2,t3;
Button b;
Label L1,L2,L3,L4;
public void init( )
{

t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
L1=new Label("enter num1");
L2=new Label("enter num2");
L3=new Label("Result is");
L4=new Label("Division of 2 numbers");
b=new Button("Divide");
add(L4);
add(L1);
add(t1);
add(L2);
add(t2);
add(L3);
add(t3);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try
{
SMVEC-Department of Information Technology Page 41
IT T45- Java Programming

int num1=Integer.parseInt(t1.getText());
int num2=Integer.parseInt(t2.getText());
t3.setText(String.valueOf(num1+num2));
}
catch(ArithmeticException a)
{
JOptionPane.showMessageDialog(null,"Divide by zero");
}
catch(NumberFormatException b)
{
JOptionPane.showMessageDialog(null,"NumberFormateException");
}
}
}
/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/

Explanation :
The above java program begins with two import statements. The first import statement imports
the Applet class from applet package. Every AWT-based(Abstract Window Toolkit) applet that you
create must be a subclass (either directly or indirectly) of Applet class. The second statement import
the Graphics class from awt package.

Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not
begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an applet
begins execution when the name of its class is passed to an applet viewer or to a network browser.
passing parameters to applets.

4.9.2 Running the HelloWorld Applet :

After you enter the source code for Division.java, compile in the same way that you have been
compiling java programs(using javac command). However running HelloWorld with the java command
will generate an error because it is not an application.

>java HelloWorld

Error: Main method not found in class HelloWorld, please define the main method as:
public static void main(String[] args)

There are two standard ways in which you can run an applet :
 Executing the applet within a Java-compatible web browser.
 Using an applet viewer, such as the standard tool, appletviewer.
SMVEC-Department of Information Technology Page 42
IT T45- Java Programming

An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test
your applet.

Using java enabled web browser : To execute an applet in a web browser we have to write a short
HTML text file that contains a tag that loads the applet. We can use APPLET or OBJECT tag for this
purpose. Using APPLET, here is the HTML file that executes Division :

<applet code="Division" width=200 height=60>


</applet>

The width and height statements specify the dimensions of the display area used by the applet. The
APPLET tag contains several other options. After you create this html file, you can use it to execute the
applet.

NOTE : Chrome and Firefox no longer supports NPAPI (technology required for Java applets).

Using appletviewer : This is the easiest way to run an applet. To execute Division with an applet
viewer, you may also execute the HTML file shown earlier.
For example, if the preceding HTML file is saved with
RunDivision.html, then the following command line will run HelloWorld :
>appletviewer RunHelloWorld.html
HelloWorld Applet

appletviewer with java source file : If you include a comment at the head of your Java source code
file that contains the APPLET tag then your code is documented with a prototype of the necessary
HTML statements, and you can run your compiled applet merely by starting the applet viewer with
your Java source code file.

import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/

>appletviewer HelloWorld

SMVEC-Department of Information Technology Page 43


IT T45- Java Programming

4.10 Passing Parameters to Applet:

Java applet has the feature of retrieving the parameter values passed from the html page. So,
you can pass the parameters from your html page to the applet embedded in your page. A great benefit
of passing applet parameters from HTML pages to the applets they call is portability. If you pass
parameters into your Java applets, they can be portable from one web page to another, and from one
web site to another. Parameters specify extra information that can be passed to an applet from the
HTML page. Parameters are specified using the HTML’s param tag.

Steps to accomplish this task -:

 To pass the parameters to the Applet we need to use param attribute of <applet> tag.
 To retrieve a parameter's value, we need to use getParameter() method of Applet class.

Signature of getParamter() method:

public String getParameter(String name)

Method takes a String argument name, which represents the name of the parameter which was specified
with the param attribute in the <applet> tag.

Method returns the value of the name parameter(if it was defined) else null is returned.

Param Tag

The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two attributes: name and
value which are used to specify the name of the parameter and the value of the parameter respectively.
For example, the param tags for passing name and age parameters looks as shown below:

<param name=‖name‖ value=‖Rajesh‖ />

<param name=‖age‖ value=‖25″ />

Now, these two parameters can be accessed in the applet program using the getParameter() method of
the Applet class.

Example: Details.java
import java.awt.*;

import java.applet.*;

public class Details extends Applet

String name;

String age;
SMVEC-Department of Information Technology Page 44
IT T45- Java Programming

String sport;

String food;

String fruit;

String destination;

public void init()

name = getParameter("Name");

age = getParameter("Age");

food = getParameter("Food");

fruit = getParameter("Fruit");

destination = getParameter("Destination");

sport = getParameter("Sport");

public void paint(Graphics g)

g.drawString("Reading parameters passed to this applet -", 20, 20);

g.drawString("Name -" + name, 20, 40);

g.drawString("Age -" + age, 20, 60);

g.drawString("Favorite fruit -" + fruit, 20, 80);

g.drawString("Favorite food -" + food, 20, 100);

g.drawString("Favorite destination -" + name, 20, 120);

g.drawString("Favorite sport -" + sport, 20, 140);

SMVEC-Department of Information Technology Page 45


IT T45- Java Programming

Information.html

<html>

<head>

<Title> Passing Parameters to applet</Title>

<head>

<body>

<applet code="Applet8" width="400" height="200">

<param name="Name" value="Roger">

<param name="Age" value="26">

<param name="Sport" value="Tennis">

<param name="Food" value="Pasta">

<param name="Fruit" value="Apple">

<param name="Destination" value="California">

</applet>

</body>

</html>

>appletviewer Information.html

SMVEC-Department of Information Technology Page 46


IT T45- Java Programming

Two Marks

1. What do you mean by Events in Java?


An event in Java is an object that is created when something changes within a graphical user
interface. If a user clicks on a button, clicks on a combo box, or types characters into a text field,
etc., then an event triggers, creating the relevant event object.

2. How event handling is achieved in java?


Event handling in Java is comprised of three key elements:
 Event source-which is an object that is created when an event occurs.
 Event listener-the object that "listens" for events and processes them when they occur.
 Event Object- Created when an event occurs (i.e., user interacts with a GUI component). It
contains all necessary information about the event that has occurred such as:
 Type of event that has occurred
 Source of the event
It is represented by an Event class.

3. How Event Listener Registers the event to Event Source(or) Define Event Listeners
A listener should be registered with a source .Once registered, listener waits until an event
occurs
When an event occurs
 An event object created by the event source
 Event object is fired by the event source to the registered listeners (method of event listener is
called with an event object as a parameter)

4. List some Event Listeners used in java?


Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
 ActionListener
 AdjustmentListener
 ComponentListener
 ContainerListener
 FocusListener
 ItemListener

5. What do you mean by Delegation Event Model?


Event handling is delegated to different objects and methods .The idea is that events are processed
by event listeners, which are separate objects that handle specific types of events.

 The listener registers and specifies which events are of interest (for instance mouse events).
 Only those events that are being listened for will be processed.

SMVEC-Department of Information Technology Page 47


IT T45- Java Programming

6. What is the need of Adapter Class?

They are built-in in Java class which implement all methods of each listener interface with more
than one method. Implementations of the methods are all empty. They are useful when we want to
listen and process only some of the events that are handled by one particular event listener interface.

7. Define the term AWT?

AWT (Abstract Window Toolkit) was Java’s first GUI framework, which was introduced in
Java 1.0. It is used to create GUIs (Graphical User Interfaces). Java AWT components are platform-
dependent i.e. components are displayed according to the view of operating system. AWT is
heavyweight i.e. its components are using the resources of OS.

8. List the features of AWT and AWT hierarchy .


AWT features :
 A set of native user interface components. A robust event-handling model

 Graphics and imaging tools, including shape, color, and font classes

 Layout managers, for flexible window layouts that do not depend on a particular window size or
screen resolution

 Data transfer classes, for cut-and-paste through the native platform clipboard

Hierarchy of Java AWT classes


9. Write short notes on Frame class?
Frame is a subclass of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT applications
are created using Frame window.

SMVEC-Department of Information Technology Page 48


IT T45- Java Programming

10. How does a Panel class differ from the Frame class?

Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
border. It is container that is used for holding components. A panel provides space in which an
application can attach any other component, including other panels.

11. Write about the Component class


Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible for remembering
the current foreground and background colors and the currently selected text font.
12. Write about the Container
Container is a component in AWT that contains another component like button, text field,
tables etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.

13. How does Graphics Class helps to draw objects in java?

The Graphics class provides the framework for all graphics operations within the AWT. The Graphics
class is an abstract class that provides the means to access different graphics devices. It is the class that
lets you draw on the screen, display images, and so forth.

The graphics context is encapsulated by the Graphics class and is obtained in two ways:

• It is passed to a method, such as paint( ) or update( ), as an argument.

• It is returned by the getGraphics( ) method of Component.

14. Define Applet

Applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. Applet is embedded in a HTML page using the APPLET or OBJECT tag and
hosted on a web server. Applets are used to make the web site more dynamic and entertaining.

There are two ways to run an applet


 By html file.
 By appletViewer tool (for testing purpose).

15. Difference between applets and applications

Applet
Application
A small Program that performs a specific task
A standalone program that is designed to run on
that run within a particular environment and need
a standalone machine to perform a task
a plug in.
Small Program Large Program

SMVEC-Department of Information Technology Page 49


IT T45- Java Programming

Can be executed on stand alone computer


Used to run a program on client Browser
system
Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client
JAVA supported browser. machine.

Applet applications are executed in a Restricted Application can access all the resources of the
Environment. It cannot read and write the files computer. It can perform File reading and
form the local computer writing on the local computer
Applets are created by extending the Applications are created by writing public static
java.applet.Applet void main(String[] s) method.
Applet application has 5 methods which will be
Application has a single start point which is
automatically invoked on occurrence of specific
main method
event
Example:
import java.awt.*;
import java.applet.*;
public class Myclass extends Applet
public class MyClass
{
{
public void init() { }
public static void main(String args[]) {}
public void start() { }
}
public void stop() {}
public void destroy() {}
public void paint(Graphics g) {}
}

16. Draw the Life Cycle Of An Applet (or) What are the methods involved in applet life cycle.
Java applet inherits features from the class Applet. Thus, whenever an applet is created, it
undergoes a series of changes from initialization to destruction. Various stages of an applet life cycle
are depicted in the figure below:

SMVEC-Department of Information Technology Page 50


IT T45- Java Programming

17. List the different Types of applets


Applet is java program that can be embedded into HTML pages. Java applets run on the java
enables web browsers such as Mozilla and internet explorer.
There are two type of applet in java.
 Local Applet
 Remote Applet
Local Applet:
When we create our own applet and store them to our local system then this type of applet is termed as
Local applet
Remote Applet:
A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet. we can download the remote applet on to our system via at the
internet and run it. In order to locate and load a remote applet, we must known the applets

18. Write about passing parameters to applet?

 Java applet has the feature of retrieving the parameter values passed from the html page. So, you
can pass the parameters from your html page to the applet embedded in your page.

 Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag.

SMVEC-Department of Information Technology Page 51

You might also like