The Class Applet destroy()
init()
start()
stop()
java.applet.Applet
java.awt.Panel
2
3
The Life-Cycle of Applet
init()
Calledexactlyonceinanapplet’slife.
Calledwhenappletisfirstloaded.
Usedtoreadappletparameters,startdownloading
anyotherimagesormediafiles,orsetuptheuser
interface,etc.
start()
Called by the browser or applet viewer to inform
this applet that it should start its execution.
It is called after theinitmethod
The Applet class
Tocreateanapplet,wemustimporttheAppletclass.
Thisclassisinthejava.appletpackage.
TheAppletclasscontainscodethatworkswitha
browsertocreateadisplaywindow.
TheonlywaytomakeanappletistoextendApplet.
Example:
import java.applet.Applet;
public class Drawing extends Applet {
…we still need to put some code in here...
}
7
The paint method
paintdoesn’treturnanyresult.
import java.applet.Applet;
import java.awt.*;
public class Drawing extends Applet {
public void paint(Graphics g) {
…we still need to put some code in here…
}
}
8
Java’s coordinate system
Java uses an (x, y) coordinate system
(0, 0) is the top left corner
(50, 0) is 50 pixels to the right of (0, 0)
(0, 20) is 20 pixels down from (0, 0)
(w -1, h -1) is just inside the bottom right corner,
where w is the width of the window and h is its height
12
(0, 0)
(0, 20)
(50, 0)
(50, 20)
(w-1, h-1)
14
The complete applet
import java.applet.Applet;
import java.awt.*;
public class Drawing extends Applet {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(20, 20, 50, 30);
g.setColor(Color.RED);
g.fillRect(50, 30, 50, 30);
}
}
The HTML page
You can only run an applet in an HTML page.
The HTML looks something like this:
<html>
<body>
<h1>DrawingAppletApplet</h1>
<applet code="Drawing.class"
width="250" height="200">
</applet>
</body>
</html>
15
The simplest possible applet
import java.applet.Applet;
public class TrivialApplet extends Applet { }
<applet
code="TrivialApplet.class”
width=200 height=100>
</applet>
TrivialApplet.java
TrivialApplet.html
The simplest reasonable applet
import java.awt.*;
import java.applet.Applet;
public class HelloWorld extends Applet {
public void paint( Graphics g ) {
g.drawString( "Hello World!", 30, 30 );
}
}
<html>
<applet code ="HelloWorld.class"width =“200" height = “100">
</applet>
</html>
Running the applet
Compile
javac HelloWorld.java
If no errors, bytecodes stored in HelloWorld.class
Create an HTML file
ends in .htmor .html(HelloWorld.html)
To execute an applet
appletviewer HelloWorld.html
18
Displaying Numerical values
import java.awt.*;
import java.applet.Applet;
public class abextends Applet{
public void paint(Graphics g){
int a=10, b=20;
int d=a+b;
String s= “sum:“+String.valueOf(d);
g.drawString(s, 100, 100);
}
}