Fepj - 4
Fepj - 4
Important points :
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
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
It is important to understand the order in which the various methods shown in the above image
are called. 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( )
Let’s look more closely at these methods.
1. 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.
2. 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( ).
3. 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.
Note: This is the only method among all the method mention above, which is parameterized. It’s
prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.
4. 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.
5. 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( ).
1. By html file.
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First_applet.java
import java.applet.Applet;
import java.awt.Graphics;
public class First_applet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to First Applet creation",150,150);
}
}
/*
<applet code="First_applet.class" width="300" height="300">
</applet> */
OUTPUT :
C:\Reena_JP>set path=C:\Program Files\Java\jdk-7\bin
C:\Reena_JP>javac First_applet.java
C:\Reena_JP>appletviewer First_applet.java
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.
public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.
import java.applet.Applet;
import java.awt.*;
Example :
public class GraphicsDemo extends Applet
{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} }
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Some of the methods of AudioClip class along with their description are listed in Table :
Method Description
import java.applet.*;
import java.awt.*;
public class SoundExample extends Applet
{
private AudioClip mysound;
public void init()
{
mysound=getAudioClip(getCodeBase(), “chimes.wav”);
}
public void start()
{
mysound.loop();
}
public void stop()
{
mysound.stop();
}
The HTML code for SoundExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLETCODE=”SoundExample.class” WIDTH=”200″ HEIGHT=”l30″>
</APPLET>
</CENTER>
</BODY>
</HTML>
Passing parameters to an applet.
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Event Handling
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
Foreground Events
Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of
these events are operating system failures/interrupts, operation completion, etc. As we perform event
handling in AWT or Swing, we can perform it in applet also.
Event Handling : It is a mechanism to control the events and to decide what should happen after an event
occur. To handle the events, Java follows the Delegation Event model. Let's see the simple example of
event handling in applet that prints a message by click on the button.
Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Syntax:
addTypeListener()
MouseListener & The events that occur due to the user interaction
MouseEvent MouseMotionListener with the mouse (Pointing Device).
Event Class Listener Interface Description
ActionListener
actionPerformed()
AdjustmentListener
adjustmentValueChanged()
componentResized()
componentShown()
componentMoved()
ComponentListener
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener
itemStateChanged()
keyTyped()
KeyListener
keyPressed()
Listener Interface Methods
keyReleased()
mousePressed()
mouseClicked()
mouseEntered()
mouseExited()
MouseListener
mouseReleased()
mouseMoved()
MouseMotionListener
mouseDragged()
MouseWheelListener
mouseWheelMoved()
TextListener
textChanged()
windowActivated()
windowDeactivated()
windowOpened()
windowClosed()
windowClosing()
windowIconified()
WindowListener
windowDeiconified()
Code-Approaches
The three approaches for performing event handling are by placing the event handling code in one of the
below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
An event which indicates that a mouse action occurred in a component. A mouse action is
considered to occur in a particular component if and only if the mouse cursor is over the unobscured part
of the component's bounds when the action happens. Component bounds can be obscured by the visible
component's children or by a menu or by a top-level window. This event is used both for mouse events
(click, enter, exit) and mouse motion events (moves and drags).
Mouse Events
o a mouse button is pressed
o a mouse button is released
o a mouse button is clicked (pressed and released)
o the mouse cursor enters the unobscured part of component's geometry
o the mouse cursor exits the unobscured part of component's geometry
Mouse Motion Events
o the mouse is moved
o the mouse is dragged
Adapter classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
Pros of using Adapter classes:
It assists the unrelated classes to work combinedly.
It provides ways to use classes in different ways.
It increases the transparency of classes.
It provides a way to include related patterns in the class.
It provides a pluggable kit for developing an application.
It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
AWT classes
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.Java AWT components are platform-dependent i.e. components
are displayed according to the view of operating system. AWT is heavy weight i.e. its components are
using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window. We need to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for
holding the components. It can have other components like button, text field etc. An instance of Panel
class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other
components like button, text field, scrollbar etc. Frame is most widely used container while developing
an AWT application.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager Defines the layout manager for the component.
m)
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// no layout
f.setLayout(null);
// main method
public static void main(String args[]) {
}
Output:
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality and specificity
with each level. The two most common windows are those derived from Panel, which is used by applets,
and those derived from Frame, which creates a standard application window. Much of the functionality of
these windows is derived from their parent classes. Thus, a description of the class hierarchies relating to
these two classes is fundamental to their understanding. Figure shows the class hierarchy
for Panel and Frame. Let’s look at each of these classes now.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates
all of the attributes of a visual component. Except for menus, all user interface elements that are displayed
on the screen and that interact with the user are
subclasses of Component. It defines over a hundred public methods that are responsible for managing
events, such as mouse and keyboard input, positioning and sizing the window, and repainting. (You already
used many of these methods when you created applets in Chapters 23 and 24.) A Component object is
responsible for remembering the current foreground and background colors and the currently selected text
font.
Container
The Container class is a subclass of Component. It has additional methods that allow
other Component objects to be nested within it. Other Container objects can be stored inside of
a Container (since they are themselves instances of Component). This makes for a
multileveled containment system. A container is responsible for laying out (that is, positioning) any
components that it contains. It does this through the use of various layout managers.
Panel
The Panel class is a concrete subclass of Container. A Panel may be thought of as a recursively nestable,
concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet,
it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar,
menu bar, or border. This is why you don’t see these items when an applet is run inside a browser. When
you run an applet using an applet viewer, the applet viewer provides the title and border.
Other components can be added to a Panel object by its add( ) method (inherited from Container). Once
these components have been added, you can position and resize them manually using the setLocation(
), setSize( ), setPreferredSize( ), or setBounds( ) methods defined by Component.
Window
The Window class creates a top-level window. A top-level window is not contained within any other
object; it sits directly on the desktop. Generally, you won’t create Window objects directly. Instead, you
will use a subclass of Window called Frame, described next.
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title
bar, menu bar, borders, and resizing corners. The precise look of a Frame will differ among environments.
A number of environments are reflected in the screen captures shown throughout this book.
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other type of
window that you will find valuable: Canvas. Derivedfrom Component, Canvas encapsulates a
blank window upon which you can draw.
working with frame window
In addition to the applet, the type of AWT-based window you will most often create is derived from
Frame. You will use it to create child windows within applets, and top-level or child windows for
stand-alone applications. As mentioned, it creates a standard-style window.
Here are two of Frame’s constructors:
Frame( ) throws HeadlessException Frame(String title) throws HeadlessException
The first form creates a standard window that does not contain a title. The second form creates a
window with the title specified by title. Notice that you cannot specify the dimensions of the
window. Instead, you must set the size of the window after it has been created. A
HeadlessException is thrown if an attempt is made to create a Frame instance in an environment
that does not support user interaction.
There are several key methods you will use when working with Frame windows. They are examined
here.
Setting the Window’s Dimensions
The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:
void setSize(int newWidth, int newHeight) void setSize(Dimension newSize)
The new size of the window is specified by newWidth and newHeight, or by the width and height
fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels.
The getSize( ) method is used to obtain the current size of a window. One of its forms is shown
here:
Dimension getSize( )
This method returns the current size of the window contained within the width and height fields of
a Dimension object.