// This applet demonstrates the use of the if statement. // User input consists of a TextField and an "add" button. // Positive integers input through the TextField are added // to a sum when the add button is pressed. // The sum is displayed. Non-Positive integers are ignored. import java.applet.*; import java.awt.*; import java.awt.event.*; public class Lesson5 extends Applet implements ActionListener { Label title = new Label("Sum Positive Integers"); // Input panel. Panel inputP = new Panel(new GridLayout(1, 2)); Label inputL = new Label("Enter integers:"); TextField input = new TextField(15); // Sum output. Label sumL = new Label(); // Pressing this will cause the input to be read and processed. Button addB = new Button("Add"); int sum = 0; public void init() { setLayout(new GridLayout(4, 1)); add(title); add(inputP); inputP.add(inputL); inputP.add(input); add(sumL); sumL.setText("sum: " + sum); add(addB); addB.addActionListener(this); setSize(200,100); } // actionPerformed handles button presses. It is executed whenever // the add button is pressed. public void actionPerformed(ActionEvent e) { int inputI; // Read the input integer. inputI = Integer.parseInt(input.getText()); // Ignore non-positive inputs. if (inputI > 0) { sum += inputI; sumL.setText("sum: " + sum); } } }