Home -> Workshops -> STA 2000 Java Workshop -> Converter Class

Converter Class

Copy all into Editor and save as Converter.java

import java.awt.*;
import java.awt.event.*;

public class Converter extends Frame implements ActionListener, ItemListener
{	private ConverterApplet parent = null;
	private CheckboxGroup inUnit = new CheckboxGroup();
	private CheckboxGroup outUnit = new CheckboxGroup();
	private Checkbox inUnitFeet = new Checkbox("Feet", inUnit, true);
	private Checkbox inUnitMeter = new Checkbox("Meter", inUnit, false);
	private Checkbox outUnitFeet = new Checkbox("Feet", outUnit, true);
	private Checkbox outUnitMeter = new Checkbox("Meter", outUnit, false);
	private NumberField input = new NumberField(0.0);
	private Label output = new Label("Enter number to convert");
	private MenuItem fileExit = new MenuItem("Exit");
	private class WindowCloser extends WindowAdapter
	{	public void windowClosing(WindowEvent we)
		{	parent.closeFrame(); }
	}

	public Converter(ConverterApplet _parent)
	{	super("Length Converter");
		parent = _parent;
		setup();
		fileExit.addActionListener(this);   addWindowListener(new WindowCloser());
		inUnitMeter.addItemListener(this);  inUnitFeet.addItemListener(this);
		outUnitMeter.addItemListener(this); outUnitFeet.addItemListener(this);
		validate(); pack();	show();
	}
	public void actionPerformed(ActionEvent ae)
	{	parent.closeFrame(); }
	public void itemStateChanged(ItemEvent ie)
	{	double number = input.getNumber();
		if (input.hasError)
			output.setText("Invalid input, please try again");
		else
		{	double answer = number;
			if ((inUnit.getSelectedCheckbox() == inUnitFeet) &&
					 (outUnit.getSelectedCheckbox() == outUnitMeter))
				answer = number / 3.12;
			else if ((inUnit.getSelectedCheckbox() == inUnitMeter) &&
					 (outUnit.getSelectedCheckbox() == outUnitFeet))
				answer = number * 3.12;
			output.setText(number +" " +inUnit.getSelectedCheckbox().getLabel() + 
				" = " +answer +" " +outUnit.getSelectedCheckbox().getLabel());
		}
	}
	private void setup()
	{	Menu file = new Menu("File");
		file.add(fileExit);
		MenuBar menu = new MenuBar(); menu.add(file); setMenuBar(menu);
		Panel inUnitPanel = new Panel();
		inUnitPanel.setLayout(new FlowLayout());
		inUnitPanel.add(inUnitFeet); inUnitPanel.add(inUnitMeter);
		Panel outUnitPanel = new Panel();
		outUnitPanel.setLayout(new FlowLayout());
		outUnitPanel.add(outUnitFeet); outUnitPanel.add(outUnitMeter);
		setLayout(new GridLayout(4, 2));
		add(new Label("Number: ", Label.RIGHT));	add(input);
		add(new Label("Convert from:", Label.RIGHT));	add(inUnitPanel);
		add(new Label("Convert to:", Label.RIGHT));	add(outUnitPanel);
		add(new Label("Answer:", Label.RIGHT));		add(output);
	}
}