Java Reference
In-Depth Information
The values in num0 and num1 have to be converted to type double . This is
done using static function Double.valueOf to convert a String to a value of
wrapper class Double and then function doubleValue to yield the value as a
double . The final statement stores the sum of the two values in variable sum .
Method paint is called only after init and start have finished, and inher-
ited method start does not do anything. Method paint is straightforward. It just
draws a rectangle that surrounds the text and writes the text.
Get this applet
and the next
from a footnote
on lesson page
16-3.
An applet to paint a clock
Activity 16-3.1 discusses an applet that draws a clock on the screen. The
clock is interesting because every time the clock is repainted, it obtains the time
from the time on the clock on your computer. So, if you do anything to cause the
system to call method paint , like resize the window, the clock is updated. The
applet obtains the default Locale on your computer (see Sec. 5.5.2) and uses it
Activity
16-3.1
import java.awt.*;
import java.util.*;
import java.applet.*;
import javax.swing.*;
/** An applet that requests two double values from the user and prints their sum */
public class Summing extends JApplet {
private double sum; // the sum of the two values
public void init() {
String num0; // First number, entered by user
String num1; // Second number, entered by user
double number0; // First number, as a double
double number1; // Second number, as a double
// Read in first and second numbers
num0= JOptionPane.showInputDialog("Enter first floating-point value");
num1= JOptionPane.showInputDialog("Enter second floating-point value");
// Convert the two numbers to type double and add them
number0= Double.valueOf(num0).doubleValue();
number1= Double.valueOf(num1).doubleValue();
sum= number0 + number1;
}
/** Write the results using g */
public void paint(Graphics g) {
g.drawRect(10,10,120,20);
g.drawString("The sum is " + sum, 20, 25);
}
}
Figure 16.2:
An applet to sum two numbers
Search WWH ::




Custom Search