import java.applet.Applet; import java.awt.*; import java.awt.event.*; /** * A two button Applet, can add or subtract two numbers * * @author Mr J * @version 241103 */ public class AddSub extends Applet implements ActionListener { // two text fields for the numbers private TextField number1 = new TextField(20); private TextField number2 = new TextField(20); // two buttons for the add/subtract options private Button add = new Button("+"); private Button sub = new Button("-"); // Label for the answer private Label answer = new Label("The answer will appear here"); /** * Add the objects to the Applet */ public void init() { add(number1); add(number2); add(add); add(sub); add(answer); // Causes button presses to be detected add.addActionListener(this); sub.addActionListener(this); } /** * When an event occurs on an object with an ActionListener attached, this * method is carried out. * * @param e carries details about the event that occurred */ public void actionPerformed(ActionEvent e) { int total = 0; int n1, n2; // convert the Strings from the TextFields to ints n1 = Integer.parseInt(number1.getText()); n2 = Integer.parseInt(number2.getText()); // check which button was pressed if (e.getSource()== add) { total = n1 + n2; } else // must have been sub { total = n1 - n2; } // put answer answer.setText("" + total); } }