FileDocCategorySizeDatePackage
Converter.javaAPI DocExample2922Thu Jan 10 10:55:44 GMT 2002None

Converter.java

//N.Kennedy 7/01/02
//Centigrade to Fahrenheit Converter

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;

class Converter implements ActionListener {
	JFrame frame = new JFrame("Temperature Converter");
	JTextField numberWindow = new JTextField(4); // set up global window
	public Converter() {
	  frame.getContentPane().setLayout(new GridLayout(2,1));
	  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	  //frame.pack(); // an automatic setSize
	  frame.setSize(600,200);
	  //top panel additions
	    JPanel topPanel = new JPanel();
	    frame.getContentPane().add(topPanel);
	    //and now do the image and title
	    //and set up image 
	    ImageIcon icon = new ImageIcon("duke.gif");
	    // and a label to put it in ...
	    // string, icon and position. string can contain HTML
	    JLabel imageLabel = new JLabel(
	    	"<html><font color =red size =6 >Temperature Converter V1.0</font>"+
	    	 "<p><font color=black size =3 >Nairn Kennedy 2002</font></html>",
	      icon,JLabel.RIGHT); // set up image on label
	    topPanel.add(imageLabel);
	  JPanel bottomPanel = new JPanel();
	  frame.getContentPane().add(bottomPanel);
	  //bottom panel created
	  bottomPanel.setLayout(new GridLayout(1,3));
	    
	    bottomPanel.add(numberWindow);//defined globally
	    ImageIcon fish = new ImageIcon("fishy01.gif");
	    JButton centButton = new JButton("To Centigrade",fish);
	    ImageIcon duck = new ImageIcon("duck01.gif");
	    JButton fahrButton = new JButton("To Fahrenheit",duck);
	    centButton.addActionListener(this);//set up listener. this is this object 
	    fahrButton.addActionListener(this);// another listener
	    bottomPanel.add(fahrButton);
	    bottomPanel.add(centButton);
	  frame.setVisible(true);
	}// end constructor
	
	public void actionPerformed (ActionEvent e) {
		// pick up button presses
		//which was pushed?
		if(e.getActionCommand() == "To Centigrade") {
			//do centigrade conversion
			centConvert();
		}//end if
		if(e.getActionCommand() == "To Fahrenheit") {
			fahrConvert();
		}//end if
		
	}//end ActionPerformed
	
	private void centConvert() {
		//Convert to Centigrade
		//get the figure from window, convert and replace
		double fahr = Double.parseDouble(numberWindow.getText());
		
		//convert ...
		double cent = (fahr - 32.0)*5.0/9.0;
		//and display
		//set up string in proper decimal format first
		DecimalFormat decF = new DecimalFormat("000.0");
		numberWindow.setText(decF.format(cent));
	}
	
	private void fahrConvert() {
		//convert to Fahrenheit
		//as above, get figure
		double cent = Double.parseDouble(numberWindow.getText());
		
		//convert ...
		double fahr = cent*9.0/5.0 +32.0;		//and display as above
		DecimalFormat decF = new DecimalFormat("000.0");
		numberWindow.setText(decF.format(fahr));
	}
	 
}//end Converter