import java.awt.*;

// An instance of this class models the grade of the road surface. An instance
// has a window (a Frame) that displays the grade, e.g. 0 for a flat surface,
// 4 for a 4% uphill grade, -4 for a 4% downhill grade. It can be
// changed by typing the new grade into textField and pressing a
// button. In order to remain driveable, the grade cannot be more than 10% or
// less than -10%. 
// An instance has its own thread of execution. Its method run is in superclass
// ClockedFrame.
public class RoadGrade extends ClockedFrame {

// Components for the frame
	Label label= new Label("Road Grade:   ");
	TextField textField= new TextField();
	Button button = new Button("Read new grade");

private int grade;	// grade of the road
  
// Constructor: a road-grade control, which uses clock c,
// with initial grade g
public RoadGrade(SystemClock c, int g) {
	super(c, "Grade");
	grade = g;
	add("North", label);
	add("Center", textField);
	textField.setText("" + grade);
	add("South", button);
	resize(600, 200);
	pack();
	move(135, 100);
	show();
  	}
  
// Return the current road grade.
public synchronized int readValue() {
	notifyAll();
	return(grade);
	}

// If a button was pressed, process it; otherwise, return
// result of super.action.
public boolean action(Event e, Object arg) {
	if (arg.equals(button.getLabel())) {
		// Handle press of "Read new grade". Here, method getText obtains
		// the sequence of characters in component textField on the Frame;
		// trim removes whitespace at either end of the String, and parseInt
		// converts it to an integer.
			String g= textField.getText().trim();
			int newGrade = Integer.parseInt(g);
			
			// grade must be between -10 and 10 inclusive.
			if (newGrade <= 10 && newGrade >= -10)
			   grade= newGrade;
			// if it isn't, reset the text field to the old value
			else
				textField.setText("" + grade);
				   
		return true;
		}
    return super.action(e, arg);
  	}
}

