Unit IV Java1
Unit IV Java1
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.
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.
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.
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.
General form:
Object getSource()
String toString()
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.
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.
Sources of Events
Button
Checkbox
Choice
List
Menu Item
Scrollbar
Text Components
Window
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)
getModifier( ) - method returns a value that indicates which modifier keys were pressed when the
event was generated.
int getModifier( )
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.
The getComponent( ) method returns the component that generated the event.
Component getComponent ( )
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.
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:
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:
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()
getModifier( ) - method is used to obtain a value that contains all of the original modifier flags.
int getModifiers( )
There are two types of item events which are identified by two integer constants:
ItemEvent defiens one integer constant, ITEM_STATE_CHANGED that signifies a change of state.
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 ( )
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.
KeyEvent (Component src, int type, long when, int modifiers, int code, char ch)
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.
There are eigth types of mouse events. MouseEvent class defines the following integer constants:
MouseEvent (Component src, int type, long when, int modifier, int x,int y, int clicks, boolean
triggersPopup)
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( )
MouseWheelEvent (Component src, int type, long when, int modifier, int x,int y, int clicks, boolean
triggersPopup, int scrollHow, int amont, int count)
The text event object does not include the characters currently in the text components that generated the
event.
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()
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.
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.
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.*;
msg=‖Mouse exited‖;
repaint();
}
public void mouseEntered(MouseEvent e)
{
x=0;
y=10;
msg=‖Mouse exited‖;
}
}
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
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.
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
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.*;
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.
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
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.
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.*;
Panel p1;
Button b,c;
Image backGround;
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
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:
Class constructors
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,
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 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();
}
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
import java.io.*;
import java.awt.*;
import java.awt.event.*;
Choice ch1;
CheckboxGroup cbg;
List It;
Panel p1;
TextArea ta;
SMVEC-Department of Information Technology Page 23
IT T45- Java Programming
public AwtControl()
l3 = new Label("College");
l4 = new Label("Department");
t1 = new TextField(20);
t2 = new TextField(20);
t3 = new TextField(20);
ch1.addItem("CSE");
ch1.addItem("IT");
ch1.addItem("MCA");
ch1.addItem("ECE");
p1 = new Panel();
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);
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");
dispose();
System.exit(0);
control.setSize(600,600);
control.setVisible(true);
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.
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.
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;
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:
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.
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(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)
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:
repaint( )
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( )
paint( )
Drawing Lines
Lines are drawn by means of the drawLine() method,shown here:
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 );
}
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:
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.
// Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
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.
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),
shown here:
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.
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);
}
}
Advantage of Applet
Applet Application
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) {}
}
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.
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( ).
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.
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.
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.
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 paint(Graphics g)
{
System.out.println("Paint(() called");
}
init() called
Start() called
Paint(() called
Paint(() called
Stop() Called
Start() called
Paint(() called
Stop() Called
Destroy)() Called
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
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).
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
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.
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 :
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
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.
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.
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:
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.*;
String name;
String age;
SMVEC-Department of Information Technology Page 44
IT T45- Java Programming
String sport;
String food;
String fruit;
String destination;
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
Information.html
<html>
<head>
<head>
<body>
</applet>
</body>
</html>
>appletviewer Information.html
Two Marks
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)
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.
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.
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.
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
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.
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:
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.
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
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:
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.