public class AdditionApplet extends JApplet
1: // Fig. 20.10: AdditionApplet.java
2: // Adding two floating-point numbers.
3: import java.awt.Graphics; // program uses class Graphics
4: import javax.swing.JApplet; // program uses class JApplet
5: import javax.swing.JOptionPane; // program uses class JOptionPane
6:
7: public class AdditionApplet extends JApplet
8: {
9: private double sum; // sum of values entered by user
10:
11: // initialize applet by obtaining values from user
12: public void init()
13: {
14: String firstNumber; // first string entered by user
15: String secondNumber; // second string entered by user
16:
17: double number1; // first number to add
18: double number2; // second number to add
19:
20: // obtain first number from user
21: firstNumber = JOptionPane.showInputDialog(
22: "Enter first floating-point value" );
23:
24: // obtain second number from user
25: secondNumber = JOptionPane.showInputDialog(
26: "Enter second floating-point value" );
27:
28: // convert numbers from type String to type double
29: number1 = Double.parseDouble( firstNumber );
30: number2 = Double.parseDouble( secondNumber );
31:
32: sum = number1 + number2; // add numbers
33: } // end method init
34:
35: // draw results in a rectangle on applet’s background
36: public void paint( Graphics g )
37: {
38: super.paint( g ); // call superclass version of method paint
39:
40: // draw rectangle starting from (15, 10) that is 270
41: // pixels wide and 20 pixels tall
42: g.drawRect( 15, 10, 270, 20 );
43:
44: // draw results as a String at (25, 25)
45: g.drawString( "The sum is " + sum, 25, 25 );
46: } // end method paint
47: } // end class AdditionApplet
48:
49: /**************************************************************************
50: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
51: * Pearson Education, Inc. All Rights Reserved. *
52: * *
53: * DISCLAIMER: The authors and publisher of this book have used their *
54: * best efforts in preparing the book. These efforts include the *
55: * development, research, and testing of the theories and programs *
56: * to determine their effectiveness. The authors and publisher make *
57: * no warranty of any kind, expressed or implied, with regard to these *
58: * programs or to the documentation contained in these books. The authors *
59: * and publisher shall not be liable in any event for incidental or *
60: * consequential damages in connection with, or arising out of, the *
61: * furnishing, performance, or use of these programs. *
62: *************************************************************************/