import java.awt.*;
import java.applet.Applet;
import java.util.Observable;
import java.util.Observer;
class NumTextField extends java.awt.TextField {
public int getIntValue() {
int v;
v= Integer.valueOf( getText() ).intValue();
return v;
}
public double getDoubleValue() {
double d;
d= Double.valueOf( getText() ).doubleValue();
return d;
}
public void setValue( int v ) {
setText( String.valueOf( v ) );
}
public void setValue( double v ) {
setText( String.valueOf( v ) );
}
}
// local storage
private double theHBU;
private double theAlpha;
private double theWeight;
// class-level constants -- what did the user change?
private static final int HBU= 1;
private static final int ALPHA= 2;
private static final int WEIGHT= 3;
// state of the updates
private int lastSet= 0;
private int priorSet= 0;
private void set( int item ) {
if( item != priorSet || item != lastSet ) {
priorSet= lastSet; lastSet= item;
}
if( priorSet != 0 && lastSet != 0 ) {
if( priorSet != WEIGHT && lastSet != WEIGHT )
theWeight= theHBU / theAlpha;
if( priorSet != HBU && lastSet != HBU )
theHBU= theAlpha * theWeight;
if( priorSet != ALPHA && lastSet != ALPHA )
theAlpha= theHBU / theWeight;
setChanged(); notifyObservers();
}
}
public void setHBU( int hbu ) {
theHBU= (double)hbu; set( HBU ); }
public void setAlpha( double alpha ) {
theAlpha= alpha; set( ALPHA ); }
public void setWeight( double weight ) {
theWeight= weight; set( WEIGHT ); }
public int getHBU() { return (int)theHBU; }
public double getAlpha() { return theAlpha; }
public double getWeight() { return theWeight; }
// the hops model
Hops theHops;
// useful view items
NumTextField hbu, alpha, ounces;
public void init() {
setLayout( new GridLayout(0,2) );
add( new Label("HBU's",Label.RIGHT) );
hbu= new NumTextField();
add( hbu );
add( new Label("Alpha Acid %",Label.RIGHT) );
alpha= new NumTextField();
add( alpha );
add( new Label("Ounces",Label.RIGHT) );
ounces= new NumTextField();
add( ounces );
theHops= new Hops();
theHops.addObserver( this );
}
public boolean action(Event evt,Object what) {
//System.err.println(evt); // debugging option
showStatus("");
if( evt.target == hbu ) {
try{
theHops.setHBU( hbu.getIntValue() );
}
catch( NumberFormatException e ) {
showStatus("HBU's invalid");
hbu.selectAll();
hbu.requestFocus();
}
}
// same for other two fields
// some obvious redundancy here, looks like a better design is required
return false;
}
public void update( Observable obj, Object what ) {
hbu.setValue( theHops.getHBU() );
alpha.setValue( theHops.getAlpha() );
ounces.setValue( theHops.getWeight() );
}