Applet
Applet
1
Applications
2
Applets
3
(C) 2010 Pearson Education, Inc. All rights
reserved.
A First Java Applet
• To compile: javac WelcomeApplet.java
– creates WelcomeApplet.class
• To execute:
– create Welcome.html
<html>
<applet code="WelcomeApplet.class" width=300 height=45>
</applet>
</html>
- In Command Prompt
>appletviewer Welcome.html
5
(C) 2010 Pearson Education, Inc. All rights
reserved.
• Class JApplet (package javax.swing) is used to create
applets.
• Every applet contains at least one public class declaration.
• An applet container can create only objects of classes that are
public and extend JApplet (or its superclass Applet).
• An applet container expects every applet to have methods named
init, start, paint, stop and destroy, each of which is
declared in class JApplet.
– These methods can be overridden (redefined) to perform tasks that are
specific to your applet.
• When an applet container loads class WelcomeApplet, the
container creates a WelcomeApplet object, then calls its
methods init, start and paint in sequence.
• Inheriting the “default” versions of these methods guarantees that
the applet container can execute each applet uniformly.
(C) 2010 Pearson Education, Inc. All rights
reserved.
• Override method paint to draw on an applet.
• Method paint receives a parameter of type
Graphics, which is used to draw graphics on
the applet.
• The applet container calls paint to tell the
applet when to draw, and the applet container
is responsible for passing a Graphics object
as an argument.
public void init() { // This method will get the specified parameter's value // out of the HTML code that is
calling the applet.
parameter1 = getParameter("param1"); // Since those are read as text we need to transform them // to
integers
parameter2 = Integer.parseInt(getParameter("param2"));
parameter3 = Integer.parseInt(getParameter("param3"));
result = parameter2 + parameter3; }
public void paint(Graphics g) { // Shows what was in the HTML param code. g.drawString("Parameter 1 is: " +
parameter1,20,20);
g.drawString("Parameter 2 is: " + parameter2,20,40);
g.drawString("Parameter 3 is: " + parameter3,20,60);
g.drawString("Parameter 2 + parameter 3 is: " + result,20,80);
}
}
Draw a sin(x) Function
import java.awt.*;
import java.applet.*;
import javax.swing.*;