Java Reference
In-Depth Information
A simple applet
Below, we show an an applet that paints text and a line. Figure 16.1 shows
the applet as displayed in a browser window —it is the grayed rectangular area.
You have seen procedure
paint
before in other contexts. For a discussion of this
procedure, see activity 1-5.5 of the CD.
Activity
16-1.2
public class
Apple
extends
JApplet {
public void
paint(Graphics g) {
g.drawString(" Hello World! ", 30, 30);
g.drawLine(30 - 2, 30 + 2, 30 + 70, 30 + 2);
Get this applet
from a footnote
on lesson page
16-3.
}
}
An applet to sum two numbers
The applet shown in Fig. 16.2 prompts the user for two floating-point num-
bers and then prints their sum in the applet panel. The applet does this only once
because the statements that perform the request appear in
init
and not in
paint
.
Initially, the applet panel is blank. The first statement in method
init
calls
method
showInputDialog
of class
JOptionPane
, which is in the Swing pack-
age. See Sec. 17.5.1. This method displays a dialog window on the screen, which
contains the argument of the call and a text field. The user is expected to type a
number and hit the return key or press button
OK
. When this has been done, the
window disappears, and the number that was typed is returned as the value of the
function call. In this case, the value is stored (as a
String
) in variable
num0
.
In the same way, the next statement displays a dialog window and stores the
number that the user types into variable
num1
. Method
showInputDialog
makes
it easy to obtain input from users.
Activity
16-3.2
Figure 16.1:
An applet to demonstrate procedure
paint
Search WWH ::
Custom Search