Line-by-line the code reads as follows:import java.applet.Applet; import java.awt.Graphics; public class EchoApplet extends Applet { String s; public void init () { s = getParameter("text"); if (s == null) s = "What, no parameter to echo?"; } public void paint(Graphics g) { g.drawString(s, 40, 50); g.drawString(s, 40, 70); } }
import
statements: by importing the
java.applet.Applet
and java.awt.Graphics
classes
we can later refer to these classes by the short names Applet
and Graphics
and we have access to the classes of the
Java development environment for creating applets and for drawing
graphics on the screen.
java.applet.Applet
class. So it has access to all methods for creating and using applets.
For example, we can use the method getParameter
in this
class to pass parameters from the Web page to our applet.
The extends
keyword indicates that EchoApplet
is a subclass of the Applet
class.
The EchoApplet
class is declared public
so that it
can be accessed by the parent class.
String s;
we only declare s
to be
a String
class. In the initialization of the applet,
when we assign a value to it, an object or instance of this class
is created with the name s
.
init
methodinit
of the applet
consists of reading the parameter text
from the
Web page that includes the applet and of creating an object or
instance of the String
class with the name
s
having the value of text
.=
is used for assignment.if
-clause we check whether
the parameter text
is indeed present in the Web page, and
if not, we initialize the string s
to What, no
parameter to echo?.==
is used for equality testing and
null
is a special value that indicates that a variable does
not refer to any object.
In the case of no parameter passed to the applet, i.e., in case the
PARAM
tag is not present, you should see on the
screen something like the following
The
init
method is invoked only once when
the applet is loaded in the Web browser or appletviewer.
paint
methodpaint
takes care
of the two echoes. The Graphics
object g
passed
into the paint
method refers to the
applet's on-screen drawing context. The first argument to the
Graphics drawString
method is the string to draw
onscreen. The second and third arguments are the (x,y)
position of
the lower left corner of the text onscreen. The applet's coordinate
system starts at (0,0), which is at the upper left corner of the
applet's display area. The positive x direction is to the right and the
positive y direction is downward.
Let us look once more on the way the drawString
method is called.
It is an example of the following more general dot-notation:
object.
method(arguments).
First you mention the receiving object, then you
select some method from the class to which the object belongs,
and finally you apply the chosen method on the arguments.