import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DistanceGUIFrame extends JFrame 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
   // Constructor 
   public DistanceGUIFrame() {
     // Declare local variables
     JLabel inputLab = new JLabel("Input distance >>");
     JPanel dataPanel = new JPanel();  
     JPanel buttonPanel = new JPanel();

     // Define the layout manager for the frame
     getContentPane().setLayout(new FlowLayout());

     // Fill dataPanel and add it to frame
     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 the frame
     buttonPanel.add(toKms);
     buttonPanel.add(toMiles);
     getContentPane().add(buttonPanel);

     // Add output text area to the frame
     getContentPane().add(output);

     // Register frame as listener for button presses
     toMiles.addActionListener(this);
     toKms.addActionListener(this);
   }

   public void actionPerformed(ActionEvent aE) {
     String inputStr = input.getText();
     double inputDist = Double.parseDouble(inputStr);
     double outputDist;
     DistanceConverter dC = new DistanceConverter();

     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
  }

  public static void main(String[] args) {
     DistanceGUIFrame dGUI = new DistanceGUIFrame();
     dGUI.setSize(300, 200);
     dGUI.setVisible(true);
     dGUI.setTitle("Distance Conversion");
     dGUI.addWindowListener(
        new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
              System.exit(0);
           }
        }
     );
  }
}
   


