Вы находитесь на странице: 1из 54

Applets

Applets are small java programs that can be transported over the
internet from one computer to another and run using the Applet
viewer or any web browser that supports java. All applets are
subclasses of Applet. Thus, all applets must import java.applet.
Applets must also import java.awt. (AWT stands for the Abstract
Window Toolkit)Since all applets run in a window, it is necessary to
include support for that window.
Execution of an applet does not begin at main( ). Instead, execution
of an applet is started and controlled with an entirely different
mechanism. Once an applet has been compiled, it is included in an
HTML file using the APPLET tag.The applet will be executed by a
Java-enabled web browser when it encounters the APPLET tag
within the HTML file.
The applet tag in the html file
<applet code="MyApplet" width=200 height=60>
</applet>
The Applet Class
Applet provides all necessary support for applet execution, such
as starting and stopping. It also provides methods that load
and display images, and methods that load and play audio
clips.
Applet extends the AWT class Panel. In turn, Panel extends
Container, which extends Component. These classes provide
support for Java's window-based, graphical interface. Thus,
Applet provides all of the necessary support for window-
based activities.
applets override a set of methods by which the browser or
applet viewer interfaces to the applet and controls its
execution. Four of these methods—init( ), start( ), stop( ), and
destroy( )—are defined by Applet.
Another, paint( ), is defined by the AWT Component class.
When an applet begins, the AWT calls the following methods, in
this sequence:
init( ) start( ) paint( )
When an applet is terminated, the following sequence of method
calls takes place: stop( ) destroy( )
init( )
The init( ) method is the first method to be called. This is
whereyou 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. Whereas init( ) is
called once—the first time an applet is loaded—
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 your applet's output
must be redrawn. 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 isrequired.
stop( )
The stop( ) method is called when a web browser leaves the
HTML document containing the applet—when it goes to
another 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( ).
Simple Applet Display Methods
void drawString(String message, int x, int y)
message is the string to be output beginning at x,y. In a Java
window, the upperleft corner is location 0,0.
void setBackground(Color newColor)
void setForeground(Color newColor)
To set the background and the forground color.
Color.black Color.magenta Color.blue Color.orange
Color.cyan Color.pink Color.darkGray Color.red
Color.gray C olor.white Color.green Color.yellow
Color getBackground( )
Color getForeground( )
To obtain the current settings for the background and
foreground colors
Ex: import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class Sample extends Applet
{ String msg;
public void init()
{setBackground(Color.cyan); setForeground(Color.red);
msg = "Inside init( ) —“; }
public void start()
{ msg += " Inside start( ) —";
}
public void paint(Graphics g)
{ msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
repaint() method
• Whenever our applet needs to update the information
displayed in itswindow, we can call the repaint( ) method
which calls the paint() method
import java.awt.*;
import java.applet.*;
/*<applet code="SimpleBanner" width=300 height=50>
</applet>*/
public class SimpleBanner extends Applet implements Runnable
{ String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;
public void init()
{ setBackground(Color.cyan);
setForeground(Color.red);
}
public void start()
{ t = new Thread(this);
stopFlag = false;
t.start();
}
public void run()
{ char ch;
for( ; ; ) {
try { repaint(); Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length()); msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
} }
public void stop()
{ stopFlag = true;
t = null;
}
public void paint(Graphics g)
{ g.drawString(msg, 50, 30);
}}
Passing parameters to applet
The PARAM tag allows you to specify applet-specific arguments in
an HTML page.Applets access their attributes with the
getParameter( ) method.
< PARAM NAME = AttributeName VALUE = AttributeValue>
< PARAM NAME = AttributeName2 VALUE = AttributeValue>
...
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
</applet>
*/
public class ParamDemo extends Applet
{ String fontName;
int fontSize;
public void start()
{ String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null)
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;}
Font f=new Font(fontName,Font.BOLD,fontsize);
this.setFont(f);}
public void paint(Graphics g)
{ g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
}}
The HTML APPLET Tag
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
• CODEBASE
CODEBASE specifies the directory that will be searched for the
applet's executable class file (specified by the CODE tag). The
HTML document's URL directory is used as the CODEBASE if
this attribute is not specified.
CODE
CODE is a required attribute that gives the name of the file
containing your applet‘s scompiled .class file.
• ALT
The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser understands
the APPLET tag but can't currently run Java applets.
NAME
NAME is an optional attribute used to specify a name for the
applet instance. Applets must be named in order for other
applets on the same page to find them by name and
communicate with them.
WIDTH and HEIGHT
WIDTH and HEIGHT are required attributes that give the size (in
pixels) of the applet display area.
ALIGN
• ALIGN is an optional attribute that specifies the alignment of
the applet. LEFT, RIGHT, TOP,BOTTOM, MIDDLE
VSPACE and HSPACE
These attributes are optional. VSPACE specifies the space, in
pixels, above and below the applet. HSPACE specifies the
space, in pixels, on each side of the applet.
• PARAM NAME and VALUE
The PARAM tag allows you to specify applet-specific arguments
in an HTML page.Applets access their attributes with the
getParameter( ) method.
getDocumentBase( )
• returns the directory holding the HTML file that started the
applet
getCodeBase( )
Returns directory from which the applet's class file was
loaded
• Loading an Image
To load an image use the the getImage( ) method
defined by the Applet class. It has the following forms:
Image getImage(URL url)
• returns an Image object that encapsulates the image found
at the location specified by url.
Image getImage(URL url, String imageName)
• returns an Image object that encapsulates the image found
at the location specified by url and having the name specified
by imageName.
• Displaying an Image
• We can display an image by using drawImage( ), which is a
member of the Graphics class. Syntax:
boolean drawImage(Image imgObj, int left, int top,
ImageObserver imgOb)
This displays the image passed in imgObj with its upper-left
corner specified by left and top. imgOb is a reference to a
class that implements the ImageObserver interface.
(note:This interface is implemented by all AWT components).
/* <applet code="Load" width=248 height=146>
</applet>*/
import java.awt.*; import java.net.URL;
import java.applet.*;
public class Load extends Applet
{ Image img;
public void init()
{ URL u=null;
try{ u=new URL("file:/c:/s3mca21/viv.jpg");
}catch(MalformedURLException e){System.out.println(e);}
img = getImage(u);
}
public void paint(Graphics g)
{ g.drawImage(img, 0, 0, this);
}
}
Playing Audio Files using Applet
Create an audioclip object by using the getAudioClip() method
defined in the Applet class . syntax.
AudioClip getAudioClip(URL url)
AudioClip getAudioClip(URL url,String clipName)
Then play the AudioClip object using the Play() method of the
AudioClip class
Also we can stop the audioclip by using the stop method of the
AudioClip class
/* <applet code="Load" width=248 height=146>
</applet>*/
import java.awt.*; import java.applet.*;
import java.net.URL;
public class Load extends Applet
{ AudioClip g=null;
URL u=null;
public void init()
{ try{ u=new
URL("file:/c:/nisha/die.au");}catch(MalformedURLException
e){System.out.println(e);}
g = getAudioClip(u);
}public void paint(Graphics g1)
{ g.play();}
public void stop(){ g.stop() }}
• Working with Graphics
The AWT supports a rich set of graphics methods. All graphics
are drawn relative to a window. The origin of each window is
at the top-left corner and is 0,0. Coordinates are specified in
pixels. All output to a window takes place through a
graphics context.
Drawing Lines
Void drawLine(int startX, int startY, int endX, int endY)
Draw a line that begins at startX,startY and ends at endX,endY.
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and
filled rectangle,respectively.
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
To draw a rounded rectangle, use drawRoundRect( ) or
fillRoundRect( ),
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 top,left. The dimensions of the rectangle
are specified by width and height. The diameterof the
rounding arc along the X axis is specified by xDiam. The
diameter of the rounding arc along the Y axis is specified by
yDiam.
• Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval(
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.
• Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( )
void drawArc(int top, int left, int width, int height, int
startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,
int sweepAngle)
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.
• Drawing Polygons
• It is possible to draw arbitrarily shaped figures using
drawPolygon( ) and fillPolygon( )
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.
Event Handling
Event is an object that specifies the change of state in the
source.it is generated whenever an action takes place like a
mouse button is clicked or text is modified.when action takes
place an event is generated .the generated event and all the
information about it such as time of its occurrence ,type of
event etc, are sent to the appropriate event handling code
provided within the program.
Event Handling
It is based on the concept of source and listener .
Event source : is an object that generates a particular kind of
event.An event is generated when the internal state of an
event source is changed.
EventListener:is an object which receives notification when an
event occurs.
• The source generates an event and sends it to one or more
listeners.On receiving the event ,listener processes the event
and returns it.The source has a registered list of listeners
which will receive the events as they occur.only the listeners
that have been registered actually receive the notification
when a specific event is generated.
• Click the button Button
EventGenerated
notifies the listener
Listenerhandle it

Object Obj of ActionEvent


Click the button isgenerated
Button

actionPerformed(ActionEvent e)
method of ActionListener is
executed
The general form of method to register a listener is:
Public void addTypeListener(TypeListener eventListener)
The general form of method to unregister a listener is:
Public void removeTypeListener(TypeListener eventListener)
EventHandling
Java provides various classes and interfaces to handle the
generated events
Event classes
Event classes encapsulates all types of events occuring in the
system.the supercalss of all these event is the EventObject
class.EventObject class belongs to java.util package.
EventClass Description

ActionEvent Is generated when a user selects a menu item,


presses a button or double clicks a listitem
AdjustmentEvent Is generated when a change has been occurred in the
scroll bar.
ItemEvent When a checkbox or list item is clicked ,also occurs
when a choice selection is made

KeyEvent When the user interacts with the application through


the keys
MouseEvent When the user interacts with the application through
the Mouse

TextEvent When the users enters or changes text in textfields or


text areas.
WindowEvent When the state of the window changes
EventSource Description
Button Generates ActionEvents when the button is pressed
Window Generates window Events when the state of the
window changes
Text components Generates TextEvents when a text is entered in
textfield or text area
Menu item Generates actionevents when a menu item is
selected.
Checkbox Generates ItemEvents when a checkbox is selected
or deselected
List Generates action events when an item is
doubleclicked,generates ActionEvents when an item
is selected or deselected.
ScrollBars Generates Adjustmentevents when the scrollbars is
manipulated.
• EventListener interfaces
• The ActionListener Interface
When an ActionEvent occurs the actionPerformed() method
defined by the Actionlistener interface is invoked
The general form of the actionPerformed method is
void actionPerformed(ActionEvent e)
e is the reference to an object of ActionEvent class
• The AdjustmentListener interface
• When an AdjustmentEvent occurs the
adjsutmentValueChanged() method defined by the
Adjustmentlistener interface is invoked
The general form of the adjustmentValueChanged() method is
Void adjustmentValueChanged(AdjustmentEvent e)
Where e is the reference to an object of AdjustmentEvent class.
• ItemListenerInterface
The method itemStateChanged() defined by the itemlistener
interface is invoked when the state of an item is changed.The
object of ItemEvent class is passed as method parameter.
The syntax of the method is
Void itemStateChanged(ItemEvent item)
• KeyListener interface
The methods defined in KeyListener interface are invoked when
any key is pressed or released or a character is entered.
The methods are
Void keyPressed(KeyEvent e)
Void keyReleased(KeyEvent e)
Void keyTyped(KeyEvent e)
If a key B is pressed and released three events are generated.
When a key is pressed, a KEY_PRESSED event is generated. This
results in a call to the keyPressed( ) event handler. When the
key is released, a KEY_RELEASED event is generated and the
keyReleased( ) handler is executed. If a character is
generated by the keystroke, then a KEY_TYPED event is sent
and the keyTyped( ) handler is invoked.
There is one other requirement that your program must meet
before it can process keyboard events: it must request input
focus. To do this, call requestFocus( ), which is
defined by Component. If you don't, then your program will not
receive any keyboard events.
• The MouseListener Interface and MouseMotionListener
Interface
The method s defined by the MouseListener inteface are invoked
when the mouse is clicked,pressed ,released and when the
mouse enters or exits the component.
The methods defined by the MouseMotionListener intereface
are invoked when the mouse is dragged or moved from one
position to another.The object Mouse Event is passed as
method parameter.
The methods are
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
Void mouseExited(MouseEvent e)
• The methods defined in MouseMotionListener interface is
Void mouseMoved(MouseEvent e)
Void mouseDragged(MouseEvent me)
The TextListener interface
The method textValueChanged() defined by the TextListener
interface is invoked when the text inside the text area or
textfield alters.
The syntax of the method is
Void textValueChanged(TextEvent e)
The WindowListenerInterface
The method s defined by the WindowListener inteface are
invoked when the state of the window changes.The methods
are
public void windowOpened(WindowEvent e)
invoked the first time the window is made visible.
public void windowClosed(WindowEvent e)
Invoked when a window has been closed
public void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window
public void windowActivated(WindowEvent e)
Invoked when the Window is set to be the active Window.
public void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window.
public void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized
state.
public void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal
/*<applet code=ButTextLabel width=300 height=400>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButTextLabel extends Applet implements
ActionListener
{
TextField t1; TextField t2; TextField t3;
Button bAdd; Button bsub;
Label l1; Label l2;
public void init()
{
bAdd=new Button("add"); bsub=new Button("Sub");
t1=new TextField(10); t2=new TextField(15);
t3=new TextField(15);
l1=new Label("Enter First Number");
l2=new Label("Enter Second Number");
this.add(l1); this.add(t1); this.add(l2); this.add(t2);
this.add(bAdd);
this.add(bsub); this.add(t3);
bAdd.addActionListener(this); bsub.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
if (e.getSource()==bsub)
t3.setText(x-y+"");
else t3.setText(x+y+""); } }
Write an applet program to implement a simple calculator
/*<applet code=Mouse width=300 height=400>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Mouse extends Applet implements MouseListener
{ int x=0,y=0;
String msg="";
public void init()
{ this.addMouseListener(this);
}
public void paint(Graphics g)
{ g.drawString(msg,x,y); }
public void mousePressed(MouseEvent e)
{ x=e.getX(); y=e.getY(); msg ="MousePressed";
showStatus("Mousepressed at "+x +" "+y);
}
public void mouseReleased(MouseEvent e)
{ x=20; y=50; msg="MouseReleased";
repaint();
}
public void mouseEntered(MouseEvent e)
{ x=20; y=60; msg="MouseEntered";
repaint();
}
public void mouseExited(MouseEvent e)
{ x=20; y=70; msg="MouseExited";
repaint();
}
public void mouseClicked(MouseEvent e)
{ x=e.getX(); y=e.getY(); msg="MouseClicked";
repaint();
}
}
/*<applet code=freedraw width=300 height=400>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class freedraw extends Applet implements
MouseMotionListener
{ Graphics g;
public void init()
{ this.addMouseMotionListener(this);
g=getGraphics();
}
public void mouseMoved(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
int x=e.getX();
int y=e.getY();
g.drawString(".",x,y);
}
}
Adapter Classes
An adapter class provides an empty implementation of all
methods in an event listener interface. Adapter classes are
useful when you want to receive and process only some of the
events that are handled by a particular event listener
interface. You can define a new class to act as an event
listener by extending one of the adapter classes and
Implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods,
mouseDragged( ) and mouseMoved( ). The signatures of
these empty methods defined in theMouseMotionListener
interface. If we are interested in only mouse drag events,
then simply extend MouseMotionAdapter and implement
mouseDragged( ).
Adapter Class Listener Interface
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter W indowListener
/*<applet code=adapter width=300 height=400>
</applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class adapter extends Applet
{ int x,y;
public void init()
{ this.addMouseListener(new myadapt(this));}
public void paint(Graphics g)
{ g.drawString("MouseClicked",x,y); }
}
class myadapt extends MouseAdapter
{ adapter a;
myadapt(adapter x)
{ this.a=x; }
public void mouseClicked(MouseEvent e)
{ a.x=e.getX();
a.y=e.getY();
a.repaint();
a.showStatus("Mouseclicked at "+a.x+" "+a.y);
}
}
Program for handling keyboard event
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=keyevent width=300 height=100>
</applet>*/
public class keyevent extends Applet implements KeyListener
{ String msg = "";
int X = 10, Y = 20;
public void init()
{ addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{ showStatus("Key Down"); }
public void keyReleased(KeyEvent ke)
{ showStatus("Key Up"); }
public void keyTyped(KeyEvent ke)
{ msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{ g.drawString(msg, X, Y); }
}
If you want to handle the special keys, such as the arrow or
function keys, you need to respond to them within the
keyPressed( ) handler. They are not available through
keyTyped( ).
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=keyevent width=300 height=100>
</applet>
*/
public class keyevent extends Applet implements KeyListener
{ TextField t1;
public void init()
{ t1=new TextField(15);
t1.addKeyListener(this);
this.add(t1);
//requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{ }
public void keyReleased(KeyEvent ke)
{ }
public void keyTyped(KeyEvent ke)
{
showStatus(ke.getKeyChar()+"");
ke.setKeyChar('a');
}}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=keyevent1.java width=300 height=100>
</applet>*/
public class keyevent1 extends Applet implements KeyListener
{ String msg = "";
int X = 10, Y = 20;
public void init()
{ addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{ showStatus("Key Down");
int key = ke.getKeyCode();
switch(key)
{case KeyEvent.VK_F1: msg += "<F1>";
break;
case KeyEvent.VK_F2: msg += "<F2>";
break;
case KeyEvent.VK_F3: msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP: msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT: msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT: msg += "<Right Arrow>";
break;
case KeyEvent.VK_F12: msg+="f12";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke)
{ showStatus("Key Up"); }
public void keyTyped(KeyEvent ke)
{ msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{ g.drawString(msg, X, Y);
}
}

Вам также может понравиться