HHD Site
 
 

 

 

Health and Human Development Home
  Dept of Kinesiology
 

 

HOW IS USER INPUT IMPLEMENTED IN JAVA?


Objective:    User enters two numbers and selects function.  Sum or product is displayed.

Overview:


Source code:

import java.applet.*;
import java.awt.*;

public class Demo2 extends Applet {
 private double X;
 private double Y;
 private double Z;

 private Choice op_choices;
 private int current_op;

 static final int ADD = 0;
 static final int MULT = 1;

//INITIALIZATION
public void init()  {
  this.setBackground(Color.lightGray);
 
  op_choices = new Choice();
  op_choices.addItem("Add");
  op_choices.addItem("Multiply");
  op_choices.setForeground(Color.black);
  op_choices.setBackground(Color.lightGray);
  this.add(op_choices);

  textField1 = new java.awt.TextField();
  textField1.reshape(50,10,50,25);
  add(textField1);
  label1 = new java.awt.Label("X");
  label1.reshape(10,10,20,25);
  add(label1);
}

//DECLARATIONS
java.awt.TextField textField1;
java.awt.Label label1;

//OPTION CONTROL
public boolean action(Event event, Object arg) {
  if(event.target == op_choices) {
       if(arg.equals("Add")) current_op = ADD;
       if(arg.equals("Multiply")) current_op = MULT;
       return true;
  }
  else if (event.target == textField2 && event.id == Event.ACTION_EVENT) {
      Double doubX;
      doubX = new Double(textField1.getText());
      X = doubX.doubleValue();

      Double doubY;
      doubY = new Double(textField2.getText());
      Y = doubY.doubleValue();

       switch(current_op) {
       case ADD: Z = X + Y; break;
       case MULT: Z = X*Y; break;
            }
 
     textField3.setText( String.valueOf(Z));
     return true;
     }

return true;
} // END OPTION CONTROL
} // END DEMO2


Java Output:

Instructions:
Enter values for X and Y. Select function using option controls. Hit RETURN.


Return to Welcome Page