Sie sind auf Seite 1von 26

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side. An applet like
any application program can perform arithmetic operations, display graphics, play
sounds, accept user input, create animation, and play interactive games.

Advantage of Applet
There are many advantages of applet. They are as follows:
o

It works at client side so less response time.

Secured

It can be executed by browsers running under many platforms, including


Linux, Windows, Mac Os etc.

Drawback of Applet

Plugin is required at client browser to execute applet.

How Applets differ from Applications


The differences between an applet and an application are as follows:
1. Applets dont have the main() method as in applications. Instead they
operate on an
entirely different mechanism where they are initialized by init(),started
by start(),stopped
by stop() or destroyed by destroy().
2. Unlike stand-alone apllications, applets cannot be run independently.
Applets can be embedded in HTML pages and downloaded over the
Internet whereas Applications have no special support in HTML for
embedding or downloading.
3. Applets can only be executed inside a java compatible container, such
as a browser or appletviewer whereas Applications are executed at
command line by java.exe or jview.exe.
4. Applets execute under strict security limitations that disallow certain
operations (sandbox model security) whereas Applications have no
inherent security restrictions.
5. Applets cannot read from or write to the files in the local computer.
6. Applets cannot communicate with other servers on the network.
7. Applets cannot run any program from the local computer.
1

Java Applet
8. Applets are restricted from using libraries from other languages such as C

or C++.
Applets can be embed into Web pages in two ways:

Local applet Write the applet locally and embed it into Web pages requiring
no Internet connection.

Remote applet Download the applet stored at remote computer system


(Server) via internet and embeds and run it into a Web page.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet.

Java Applet
Begin
(Load Applet)

Born

Initialization

start ( )
Stop ( )
Running
Display

Idle

start ( )
Paint ( )

destroy ( )

Dead
Destroyed
End
Exit of Browser

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.

At this stage, following tasks can be done

Create objects needed by the applet


Set up initial values
Load images or fonts
Set up colors

2. public void start(): is invoked after the init() method or browser is


maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.

Java Applet
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.

Applet Tag
The <APPLET> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires. Save it in the same directory as
the compiled applet.
Running the Applet

To run an applet, it require one of the following tools:


1. Java-enabled Web browser (such as HotJava or Netscape)
2. Java appletviewer (for testing purpose)
Appletviewer is not a full-fledged Web browser and therefore it ignores all of the
HTML tags except the part pertaining to the running of the applet.

About Applet Tag:


The syntax of the <APPLET> tag is a little more complex and includes several
attributes that can help better integrate applet into the overall design of the Web
page. The syntax of the <APPLET> tag in full form is shown as follows:
<APPLET
[ CODEBASE = codebase_URL ]
CODE = AppletFileName.class
[ ALT = alternate_text ]
[NAME = applet_instance_name ]
WIDTH = pixels
HEIGHT = pixels
[ ALIGN = alignment ]
[ VSPACE = pixels ]
[ HSPACE = pixels ]
>
[ < PARAM NAME = name1 VALUE = value1> ]
[ < PARAM NAME = name2 VALUE = value2> ]

..
[ Text to be displayed in the absence of Java ]
</APPLET>
The various attributes shown inside [ ] indicate the options that can be used
when integrating an applet into a Web page. Note that the minimum required
attributes are :
4

Java Applet
CODE = AppletFileName.Class
WIDTH = pixels
HEIGHT = pixels
Table : Attributes of APPLET Tag
Attribute
CODE =
AppletFileName.class

Meaning
Specifies the name of the applet class to be loaded. That
is, the name of the already compiled .class file in which
the executable Java bytecode for the applet is stored. This
attribute must be specified.

CODEBASE =
codebase_URL
(Optional)

Sepcifies the URL of the directory in which the applet


resides. If the applet resides in the same directory as the
HTML file, then the CODEBASE attribute may be omitted
entirely.

WIDTH= pixels

These attributes specify the width and height of the space


on the HTML

HEIGHT= pixels
Page that will be reserved for the applet.
NAME = applet_
instance_name
(Optional)

A name for the applet may optionally be specified so that


other applets on the page may refer to this applet. This
facilitates inter-applet communication.

ALIGN = alignment
(Optional)

This optional attribute specifies where on the page the


applet will appear. Possible values for alignment are: TOP,
BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM,
TEXTTOP, and BASELINE.

HSPACE = pixels
(Optional)

Used only when ALIGN is set to LEFT or RIGHT, this


attribute specifies the amount of horizontal blank space
the browser should leave surrounding the applet.

VSPACE = pixels
(Optional)

ALT = alternate_text
(Optional)

Used only when some vertical alignment is specified with


the ALIGN attribute (TOP, BOTTOM, etc.) VSPACE specifies
the amount of vertical blank space the browser should
leave surrounding the applet.
Non-Java browsers will display this text where the applet
would normally go. This attribute is optional.

If the .class file is not in the current directory, use the codebase parameter to
specify
.
the relative path if file is on the local system, or
5

Java Applet
.

the Uniform Resource Locator (URL) of the directory containing the file if it
is on a remote computer.

Passing Parameters to Applets


We can supply user-defined parameters to an applet using <PARAM.> tags.
Each <PARAM.> tag has a name attribute such as color, and a value attribute
such as red. Inside the applet code, the applet can refer to that parameter by
name to find its value.
To set up and handle parameters, we need to do two things:
1. Include appropriate <PARAM.> tags in the HTML document.
2. Provide Code in the applet to parse these parameters.

Simple example of Applet 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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}

Note: class must be public because its object is created by Java Plugin
software that resides on the browser.

myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

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.

Java Applet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

//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

Applet Hello Java Param:


import java.awt.*;
import java. applet.*;
public class HelloJavaParam extends Applet
(
String str;
Public void init ( )
(
str = get Parameter ( string ) ;
/ / Receiving
parameter value
if (str == null)
str = Java;
str = Hello + str;
/ / Using the value
)
Public void paint (Graphics g)
(
<HTML>
g.drawString
<!Parameterized
HTML(str,
file>10, 100).
)
<HEAD>
) <TITLE> Welcome to Java Applets </TITLE>
<HEAD>
<BODY>file containing the above applet:
HTML
<APPLET CODE = HelloJavaParam.class WIDTH = 400 HEIGHT = 200>
<PARAM NAME = string VALUE = Applet!>
</APPLET>
</BODY>
</HTML>

Java Applet

Save the file as HelloJavaParam .html and then run the applet using the applet
viewer as follows:
appletviewer HelloJavaParam .html

Java Applet
Table : HTML Tags and Their Functions
Tag
<HTML>.</HTML>

Function
Signifies the beginning and end of a HTML file.

<HEAD>.</HEAD>

This tag may include details about the Web page. Usually
contains <TITLE> tag within it.

<TITLE>.</TITLE>

The text contained in it will appear in the title bar of the


browser.

<BODY>.</BODY>
This tag contains the main text of the Web page. It is the
place where the <APPLET> tag is declared.
<HI>.</HI>
<H6>.<H/6>

<CENTER>.<CENTE
R>

Header tags. Used to display headings. <HI> creates the


largest font header, while <H6> creates the smallest one.
Places the text contained in it at the center of the page.

<APPLET>.>

<APPLET..> tag declares the applet details as its


attributes.

<APPLET>.</APPLE
T>

May hold optionally user-defined parameters using


<PARAM> Tags.

<PARAM>

Supplies user-defined parameters. The <PARAM> tag


needs to be placed between the <APPLET> and
</APPLET> tags. We can use as many different <PARAM>
tags as we wish for each applet.

<B><B>
Text between these tags will be displayed in bold type.
<BR>
<F>

Line break tag. This will skip a line. Does not have an end
tag.

<IMG..>

Para tag. This tag moves us to the next line and starts a
paragraph of text. No end tag is necessary.

<HR>

This tag declares attributes of an image to be displayed.

<A> </A>

Draws a horizontal rule.

<FONT>
.</FONT>

Anchor tag used to add hyperlinks.

<!........>

We can change the color and size of the text that lies in
between <FONT> and </FONT> tags using COLOR and
SIZE attributes in thetag<FONT..>.
9

Java Applet
Any text starting with a <! Mark and ending with a > mark
is ignored by the Web browser. We may add comments
here. A comment tag may be placed anywhere in a Web
page.

Displaying Numerical Values


It applets, we can display numerical values by first converting them into strings
and then using the drawstring( ) method of Graphics class. We can do this easily
by calling the ValueOf( ) method of String class. Program 14.5 illustrates how an
applet handles numerical values.
Table : Displaying numerical values
import java.awt.*;
import java.applet.*;
public class NumValues extends Applet
{
Public void paint Graphics g)
{
int value1 = 10;
int value2 20;
int sum = value1 + value2;
String s = sum: + String.valueOf (sum);
g.drawString(s, 100, 100);
}
}
The applet is run using the following HTML file:
<html>
<applet
code = NumValues.class
width = 300
height = 300 >
</applet>
</html)

10

Java Applet
Getting Input From the User
Applets treat inputs as text strings. Use TextField class of the applet package.
Once text fields are created for receiving input, type the values in the fields and
edit them.
Text Fields contain items in string form. They need to be converted to the right
form, before they are used in any computations.
Interactive input to an applet
import java.awt.*;
import java.applet.*;
public class UserIn extends Applet
{
TextField text1, text2;
Public void init ( )
{
text1 = new TextField (8);
text2 = new TextField (8);
add (text1);
add (text2);
text1.setText (O);
text2.setText (O);
Public void paint (Graphics g)
{
int x = 0, y = 0, z = 0;
String s1, s2, s;
g.drawString (Input a number in each box, 10, 50);
try
{
s1 = text1.getText ( );
x = Integer. parseInt (s1);
s2 = text2.getText ( );
y = Integer. parseInt (s2);
}
Catch (Exception ex) { }
z = x + y;
s + String.val ueOf (z) ;
g.drawString (THE SUM IS :, 10, 75);
g.drawString (s, 100, 75);
}
Public Boolean action (Event event, Object object)
{
repaint ( );
return true;
}
}

the applet Using the following steps:


11

Java Applet
1. Type and save the program (.java file)
2. Compile the applet (.class file)
3. Write an HTML document (.html file)
<html>
<applet
Code = UserIn.class
Width = 300
Height = 200 >
</applet>
</html)
4. Use the appletviewer to display the results.

12

Java Applet
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw
the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. 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.
4. public abstract void drawOval(int x, int y, int width, int height): is used
to draw oval with the specified width and height.
5. 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.
6. 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).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. 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.
10. public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current
font to the specified font.

Example of Graphics in applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

import java.applet.Applet;
import java.awt.*;
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);

13

Java Applet
12.
13.
14.
15.
16.

g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}

myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to
be displayed. The java.awt.Graphics class provide a method drawImage() to display
the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of
Image. Syntax:
1.

public Image getImage(URL u, String image){}

Other required methods of Applet class to display


image:
1. public URL getDocumentBase(): is used to return the URL of the document
in which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

1.
2.
3.
4.
5.
6.

Example of displaying image in applet:


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

public class DisplayImage extends Applet {


Image picture;

14

Java Applet
7.
8.
9.
10.
11.
12.
13.

public void init() {


picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
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
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

15

Java Applet
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.

Example of animation in applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
}
}

try{Thread.sleep(100);}catch(Exception e){}

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
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

16

Java Applet
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on
the button.

Example of EventHandling in applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>

17

Java Applet
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.

Example of EventHandling in JApplet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>

18

Java Applet
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.

Example of Painting in Applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.

myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>

19

Java Applet
Digital clock in Applet
Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's
see the simple example:

Example of Digital clock in Applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.

import
import
import
import

java.applet.*;
java.awt.*;
java.util.*;
java.text.*;

public class DigitalClock extends Applet implements Runnable {


Thread t = null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init() {
setBackground( Color.green);
}
public void start() {
t = new Thread( this );
t.start();
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
repaint();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }

}
public void paint( Graphics g ) {
g.setColor( Color.blue );
g.drawString( timeString, 50, 50 );
}

20

Java Applet
45.

}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.

myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="DigitalClock.class" width="300" height="300">
</applet>
</body>
</html>

21

Java Applet
Analog clock in Applet
Analog clock can be created by using the Math class. Let's see the simple example:

Example of Analog clock in Applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.

import
import
import
import

java.applet.*;
java.awt.*;
java.util.*;
java.text.*;

public class MyClock extends Applet implements Runnable {


int width, height;
Thread t = null;
boolean threadSuspended;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void start() {
if ( t == null ) {
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}
public void stop() {
threadSuspended = true;
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );

22

Java Applet
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.

if ( hours > 12 ) hours -= 12;


minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );
// Now the thread checks to see if it should suspend itself
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 ); // interval specified in milliseconds

}
}
catch (Exception e) { }
}

void drawHand( double angle, int radius, Graphics g ) {


angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
}
void drawWedge( double angle, int radius, Graphics g ) {
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
angle += 2*Math.PI/3;
int x2 = (int)( 5*Math.cos(angle) );
int y2 = (int)( 5*Math.sin(angle) );
angle += 2*Math.PI/3;
int x3 = (int)( 5*Math.cos(angle) );
int y3 = (int)( 5*Math.sin(angle) );
g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}
public void paint( Graphics g ) {
g.setColor( Color.gray );
drawWedge( 2*Math.PI * hours / 12, width/5, g );
drawWedge( 2*Math.PI * minutes / 60, width/3, g );
drawHand( 2*Math.PI * seconds / 60, width/2, g );
g.setColor( Color.white );
g.drawString( timeString, 10, height-10 );
}
}

23

Java Applet
myapplet.html
1.
2.
3.
4.
5.
6.

<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</html>

24

Java Applet
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter(). Syntax:
1.

public String getParameter(String parameterName)

Example of using parameter in Applet:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

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
1.
2.
3.
4.
5.
6.
7.

<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

25

Java Applet
Applet Communication
java.applet.AppletContext class provides the facility of communication between
applets. We provide the name of applet through the HTML file. It provides getApplet()
method that returns the object of Applet. Syntax:
1.

public Applet getApplet(String name){}

Example of Applet Communication


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ContextApplet extends Applet implements ActionListener{
Button b;
public void init(){
b=new Button("Click");
b.setBounds(50,50,60,50);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
AppletContext ctx=getAppletContext();
Applet a=ctx.getApplet("app2");
a.setBackground(Color.yellow);
}
}

myapplet.html
1.
2.
3.
4.
5.
6.
7.
8.

9.

<html>
<body>
<applet code="ContextApplet.class" width="150" height="150" name="app1">
</applet>
<applet code="First.class" width="150" height="150" name="app2">
</applet>
</body>
</html>

26

Das könnte Ihnen auch gefallen