/** MilesKmsConverter.java converts miles to kilometers, or vice versa.
 * @author Joel Adams, for Alice+Java.
 */
import javax.swing.*;      // JFrame, JPanel, JLabel, ...
import java.awt.*;         // GridLayout, Color, ...
import java.awt.event.*;   // ActionListener, ActionEvent, ...
import javax.swing.border.Border;

public class MilesKmsConverter extends JFrame {
	public MilesKmsConverter() {
		super("Miles-Kms");
		// set up cross-platform look and feel	
                try {
                        UIManager.setLookAndFeel(
                                        UIManager.getCrossPlatformLookAndFeelClassName() );
                } catch (Exception e) {
                        e.printStackTrace();
                }
                
		
		// build control panel
		JPanel controlPanel = new JPanel( new GridLayout(4, 1) );
		Border gap = BorderFactory.createEmptyBorder(5,5,5,5);
		controlPanel.setBorder(gap);
        // build "Miles:" label
		controlPanel.add( new JLabel("Miles:") );
		// build "Miles:" box
		myMilesBox = new JTextField(16);
		controlPanel.add(myMilesBox);
		// build "Km:" label
		controlPanel.add( new JLabel("Kilometers:") );
		// build "Km:" box
		myKmsBox = new JTextField(16);
		controlPanel.add(myKmsBox);
        // finish up and add listeners
		super.setContentPane(controlPanel);
		super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myKmsBox.addActionListener( new KmsListener() );
		myMilesBox.addActionListener( new MilesListener() );
 	}
	
	private class MilesListener implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			final double CONVERSION_FACTOR = 1.609344;
			String milesString = myMilesBox.getText();
			String kmString = null;
			if ( milesString != null && !milesString.equals("") ) {
				double miles = Double.valueOf(milesString);
				double kms = miles * CONVERSION_FACTOR;
				kmString = new Double(kms).toString();
			} else {
				kmString = "";
			}
			myKmsBox.setText(kmString);
		}
	}
	
	private class KmsListener implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			final double CONVERSION_FACTOR = 0.621371192;
			String kmString = myKmsBox.getText();
			String milesString = null;
			if ( kmString != null && !kmString.equals("") ) {
				double kms = Double.valueOf(kmString);
				double miles = kms * CONVERSION_FACTOR;
				milesString = new Double(miles).toString();
			} else {
				milesString = "";
			}
			myMilesBox.setText(milesString);
		}
	}
	
	private JTextField myMilesBox = null;
	private JTextField myKmsBox = null;
	private final static long serialVersionUID = 0;
	
	public static void main(String[] args) {
		MilesKmsConverter self = new MilesKmsConverter();
		self.setVisible(true);
		self.pack();
	}
}
