14.2 H o w D o Y o u W r i t e a n Applet? | 665
within the event handler, the code is enclosed within a try-catch statement that handles nu-
meric input errors.
importjava.applet.Applet; // Applet class
importjava.awt.event.; // Event handling classes
importjava.awt.; // Uer interface classes
public classCalculator2 extendsApplet implementsActionListener
{
public voidactionPerformed(ActionEvent event)
//Handles events from the buttons in the applet
{
doublesecondOperand; // Holds input value
String whichButton; // Holds the button's name
// Get the operand, checking for numeric format error
try
{
secondOperand = Double.parseDouble(inputField.getText());
}
catch(NumberFormatException except)
{
secondOperand = 0.0; // If error, set to zero
}
whichButton = event.getActionCommand(); // Get the button's name
if (whichButton.equals("+")) // When the name is "+"
result = result + secondOperand; // add the operand
else if(whichButton.equals("-")) // When the name is "-"
result = result – secondOperand; // subtract operand
else
result = 0.0; // Clear result to zero
register.setText("" + result); // Display result
inputField.setText(""); // Clear input
}
Because we are extending Appletrather than JApplet, the J’s have all been removed from
class names in the following declarations.
private TextField inputField; // Data field
private Label register; // Result shown on screen
private doubleresult; // Keeps current value
public voidinit()
{
Label resultLabel; // Indicates output area