Web hosting top - Chapter 3 Introduction to Java Applets 123 Lines
Chapter 3 Introduction to Java Applets 123 Lines 19 and 22 of method paint g.drawLine( 15, 10, 210, 10 ); g.drawLine( 15, 30, 210, 30 ); use method drawLine of class Graphicsto indicate that the Graphicsobject that g refers to should draw lines. Method drawLinerequires four arguments that represent the two end points of the line on the applet the x-coordinate and y-coordinate of the first end point in the line and the x-coordinate and y-coordinate of the second end point in the line. All coordinate values are specified with respect to the upper-left corner (0, 0) coordinate of the applet. Method drawLinedraws a straight line between the two end points. 3.5 Another Java Applet: Adding Floating-Point Numbers Our next applet (Fig. 3.12) mimics the application of Fig. 2.9 for adding two integers. However, this applet requests that the user enter two floating-point numbers (i.e., numbers with a decimal point such as 7.33, 0.0975 and 1000.12345). To store floating-point numbers in memory we introduce primitive data type double, which represents double-precision floating-point numbers. There is also primitive data type float for storing single-precision floating-point numbers. A double requires more memory to store a floating-point value, but stores it with approximately twice the precision of a float(15 significant digits for doublevs. seven significant digits for float). Once again, we use JOptionPane.showInputDialogto request input from the user. The applet computes the sum of the input values and displays the result by drawing a string inside a rectangle on the applet. The HTML file to load this applet into the applet- vieweris shown in Fig. 3.13. 1 // Fig. 3.12: AdditionApplet.java 2 // Adding two floating-point numbers. 3 4 // Java core packages 5 import java.awt.Graphics; // import class Graphics 6 7 // Java extension packages 8 import javax.swing.*; // import package javax.swing 9 10 public class AdditionApplet extends JApplet { 11 double sum; // sum of values entered by user 12 13 // initialize applet by obtaining values from user 14 public void init() 15 { 16 String firstNumber; // first string entered by user 17 String secondNumber; // second string entered by user 18 double number1; // first number to add 19 double number2; // second number to add 20 21 // obtain first number from user 22 firstNumber = JOptionPane.showInputDialog( 23 “Enter first floating-point value” ); Fig. 3.12An addition program in action (part 1 of 2). Fig. 3.12 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01