UnitConverter.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/**
* Class UnitConverter - Converts from one unit to another
*
* @author Chris Thiel
* @version 1.0
*/
public class UnitConverter extends Applet
{
/**
* Class That holds the UnitChoice and handles user input
*/
// instance variables
private TextField input;
private Label arrow;
private Label answer;
private UnitChoice unitIn;
private UnitChoice unitOut;
private Button convertButton;
private double in;
private double out;
public void init()
{
input = new TextField(20);
input.setText("1");
add(input);
unitIn = new UnitChoice();
unitIn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev)
{
repaint();
}
});
add(unitIn);
arrow=new Label("--->");
add(arrow);
answer= new Label(" ");
add(answer);
unitOut = new UnitChoice();
unitOut.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev)
{
repaint();
}
});
add(unitOut);
convertButton = new Button("Convert");
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev)
{
repaint();
}
});
add(convertButton);
}
public void paint(Graphics g)
{
// simple text displayed on applet
g.setColor(new Color(255,230,190));
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.black);
g.drawString("Unit Converter by Group X", 20, 60);
try{
int x= Integer.parseInt(input.getText() );
in=unitIn.toYards(x, unitIn.getSelectedIndex());
out=unitIn.fromYards(in, unitOut.getSelectedIndex());
answer.setText(out+" ");
}catch (Exception e){
input.setText("Type a number here");
answer.setText(e.getMessage());
}
}
}
UnitChoice.java
import java.awt.*;
class UnitChoice extends Choice
{
/**
* Add more choices for more units
*/
private double[] yardValues;
private int count;
public UnitChoice()
{
super();
yardValues= new double[8];
count=0;
addItem("yards", 1.0);
addItem("inches",36.0);
addItem("feet", 3.0);
addItem("rods", 1/5.5);
addItem("furlongs", 1/220.0);
addItem("miles", 1/1760.0);
}
public void addItem(String name, double yardsValue)
{
super.addItem(name);
yardValues[count]=yardsValue;
count++;
}
public double fromYards( double x, int unit)
{
return x*yardValues[unit];
}
public double toYards( double x, int unit)
{
return x/yardValues[unit];
}
}