/* DistanceGUI.java        Authors: Koffman & Wolz 
 * Applet for distance conversion.
 * Uses DistanceConverter, Swing, and AWT.
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DistanceGUI extends JApplet 
                         implements ActionListener {
   // Data fields 
   private JTextField input = new JTextField(10);
   private JTextArea output = new JTextArea(2, 20);
   private JButton toKms = new JButton("Convert to kms");
   private JButton toMiles = new JButton("Convert to miles");

   // Methods
   // postcondition: Overrides JApplet init() method. 
   public void init() {
     // Declare local variables
     JLabel inputLab = new JLabel("Input distance >>");
     JPanel dataPanel = new JPanel();  
     JPanel buttonPanel = new JPanel();

     // Define the layout manager for the applet
     getContentPane().setLayout(new FlowLayout());

     // Fill dataPanel and add it to applet
     dataPanel.add(inputLab);
     dataPanel.add(input);
     getContentPane().add(dataPanel);

     // Give the focus (cursor) to the input text field
     input.requestFocus();

     // Fill buttonPanel and add it to applet
     buttonPanel.add(toKms);
     buttonPanel.add(toMiles);
     getContentPane().add(buttonPanel);

     // Add output text area to applet
     getContentPane().add(output);

     // Register applet as listener for button presses
     toMiles.addActionListener(this);
     toKms.addActionListener(this);
   }  // end init


   // precondition: Text field input contains numeric
   //   information.
   // postcondition: Performs the conversion requested by
   //   user, placing the result in text area output.
   public void actionPerformed(ActionEvent aE) {
 
     String inputStr = input.getText();
     double inputDist = Double.parseDouble(inputStr);
     output.setText("Bad numeric string - try again");

     // Create DistanceConverter object and do conversion.
     DistanceConverter dC = new DistanceConverter();
     double outputDist; // output, result of conversion
     Object buttonPressed = aE.getSource();
     if (buttonPressed == toMiles) {
        outputDist = dC.toMiles(inputDist);
        output.setText(inputDist + " kilometers converts to\n" +
                       outputDist + " miles");
     }
     else if (buttonPressed == toKms) {
        outputDist = dC.toKilometers(inputDist);
        output.setText(inputDist + " miles converts to\n" +
                       outputDist +  " kilometers");
     }
 
     input.requestFocus();   // Gives the focus to input
   }
}

