Prelab 4: Java Applets

Reading

Minimum.java

The code below is a Java program in applet form for computing the minimum of two integers. You should recognize the minimum subroutine from class. The line numbers are for reference only and do not represent part of the actual code!

1 import java.awt.*; 2 import java.awt.event.*; 3 4 public class Minimum extends java.applet.Applet 5 implements ActionListener 6 { 7 Label label; 8 TextField t1, t2, t3; 9 Button b; 10 11 public void init() 12 { 13 label = new Label("Enter two integers:"); 14 t1 = new TextField(15); 15 t2 = new TextField(15); 16 t3 = new TextField(50); 17 b = new Button("Minimum"); 18 add(label); 19 add(t1); 20 add(t2); 21 add(b); 22 add(t3); 23 b.addActionListener(this); 24 } 25 26 public void actionPerformed(ActionEvent event) 27 { 28 Object cause = event.getSource(); 29 int x = Integer.parseInt(t1.getText()); 30 int y = Integer.parseInt(t2.getText()); 31 32 if(cause == b) 33 { 34 int min = minimum(x,y); 35 t3.setText("The minimum is " + min ); 36 } 37 } 38 39 int minimum(int a, int b) 40 { 41 if(a < b) 42 return a; 43 else 44 return b; 45 } 46 }

Here is what the applet looks like when run from a web page:

Question 1: What is an applet?

Question 2: How hard would it be to write a Java applet to compute the sum of two integers instead? Look carefully at the Minimum.java program. Notice that most of the code would be the same. Describe how you could could write a new program "Add.java" to do this by modifying/altering the Java code above. You don't need to actually write the code, a paragraph or list of steps is fine. You can refer to specific lines in the code by number.

Question 3: Describe how you could write a new program "MinMax.java" that computes both the minimum and the maximum of three integers.




Written by Tammy Bailey.
Comments?