metconv.java Example of a JApplet



//
//  metconv.java
//  
//
//  Created by Herbert J. Bernstein on 10/15/11.
//  Copyright 2011 Herbert J. Bernstein. All rights reserved.
//
//  A demonstration applet for metric-english unit conversios
//
//  This will be set up to run both as an applet and
//  as an application
//
//  The basic structure is based on the tutorial by
//  William Wilson at
//
//  http://www.dreamincode.net/forums/topic/28410-application-to-japplet-and-reverse/
//  with some useful tidbits from
//  http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html
//


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;

public class metconv extends JApplet    
{
    
    appPanel apppanel;
    JTextField valEng;
    JTextField valMet;
    JComboBox scaleEng;
    JComboBox scaleMet;
    JComboBox unitsEng;
    JComboBox unitsMet;
    String[] unitsEnglish = {"inches","feet","yards","miles","ounces","pounds","tons"};
    String[] dimsEnglish =  {     "l",   "l",    "l",    "l",     "w",     "w",   "w"};
    double[] meteng        =  {.0254,  0.3038, 0.9144, 1609.344, 28.34952, 453.59237, 907184.74000};
    double[] engeng        =  {    1.,     12.,    36.,   63360,        1.,       16.,  32000. };
    double[] engmet        =  {39.3700787401574803149, 0.035273965837869565};
    double[] scales =       
    {  
    1000000000000000000000000.,
    1000000000000000000000.,
    1000000000000000000.,
    1000000000000000.,
    1000000000000.,
    1000000000.,
    1000000.,
    1000.,
    100.,
    10.,
    1.0,
    0.1,
    0.01,
    0.001, 
    0.000001, 
    0.000000001, 
    0.000000000001, 
    0.000000000000001, 
    0.000000000000000001,
    0.000000000000000000001,
    0.000000000000000000000001};
    String[] prefixes =     
    {"yotta","zetta","exa","peta","tera","giga","mega","kilo","hecto","deca"," ",
    "deci","centi","mili","micro","nano","pico","femto","atto","zepto","yocto"};
    String[] unitsMetric =  {"meter","gram"};
    String[] dimsMetric =   {    "l",   "w"};
    double englishVal;
    double metricVal;
    double englishScale;
    double metricScale;
    

    public void updateMetric() // Update the metric values from
                              // the English values

    {  String EnglishText = valEng.getText();
        try {
            
            // get the English units value, the scale and the units
            englishVal = Double.parseDouble(EnglishText);
            String EnglishScaleText = (String)scaleEng.getSelectedItem();
            String EnglishUnitsText = (String)unitsEng.getSelectedItem();
            
            String targetdim = "l";  // tentatively assume a length
            
            metricVal = englishVal;
            englishScale = 1.;
            
            // convert the scale text to a number and multiply
            for (int ii = 0; ii < prefixes.length; ii++) {
                if (prefixes[ii].equals(EnglishScaleText)) {
                    englishScale = scales[ii];
                    metricVal *= englishScale;
                    break;
                }
            }
            
            // convert the units text to a number and multiply
            for (int ii = 0; ii < unitsEnglish.length; ii++) {
                if (unitsEnglish[ii].equals(EnglishUnitsText)) {
                    targetdim = dimsEnglish[ii];
                    metricVal *= meteng[ii];
                    break;
                }
            }
            
            // the metric system has only one unit designator for
            // each dimensional unit, so  find it
            
            for (int ii = 0; ii < unitsMetric.length; ii++) {
                if (targetdim.equals(dimsMetric[ii])) {
                    unitsMet.setSelectedIndex(ii);
                    break;
                }
            }
            
            // now we need to find an appropriate scale for the
            // value we are using
            
            metricScale = scales[scales.length-1];
            int metricScaleIndex = scales.length-1;
            
            for (int ii = scales.length-1; ii >= 0; ii--) {
                if (metricVal < scales[ii]*9.99999) {
                    metricScale = scales[ii];
                    metricVal = metricVal/metricScale;
                    metricScaleIndex = ii;
                    break;
                }
            }
            
            scaleMet.setSelectedIndex(metricScaleIndex);
            valMet.setText(Double.toString(metricVal));
        }catch (NumberFormatException nfe) {
            valEng.setText("Please enter a valid number: " + nfe.getMessage());
        }
    }
    
    public void updateEnglish() // Update the English values from
                               // the metric values
    
    {  String MetricText = valMet.getText();
        try {
            
            // get the metric units value, the scale and the units
            metricVal = Double.parseDouble(MetricText);
            String MetricScaleText = (String)scaleMet.getSelectedItem();
            String MetricUnitsText = (String)unitsMet.getSelectedItem();
            int euIndex, euIndexNext;
            
            // System.out.println("Metric Scale text: "+MetricScaleText);
            
            String targetdim = "l";  // tentatively assume a length
            
            englishVal = metricVal;
            metricScale = 1.;
            
            // convert the scale text to a number and multiply
            for (int ii = 0; ii < prefixes.length; ii++) {
                if (prefixes[ii].equals(MetricScaleText)) {
                    // System.out.println(" index : "+ii+" scales[ii]: "+scales[ii]);
                    metricScale = scales[ii];
                    englishVal *= metricScale;
                    break;
                }
            }
 
            // System.out.println("metricVal after scaling: " +englishVal);

            // convert the units text to a number and multiply
            for (int ii = 0; ii < unitsMetric.length; ii++) {
                if (unitsMetric[ii].equals(MetricUnitsText)) {
                    targetdim = dimsMetric[ii];
                    englishVal *= engmet[ii];
                }
            }
            
            // the English system has several unit designators for
            // each dimensional unit, so start with the smallest
            // that matches
            euIndex = 0;
            euIndexNext = 0;

            for (int ii = 0; ii < unitsEnglish.length; ii++) {
                if (targetdim.equals(dimsEnglish[ii])) {
                    unitsEng.setSelectedIndex(ii);
                    euIndex = ii;
                    euIndexNext = ii;
                    if (ii+1 < unitsEnglish.length
                        && targetdim.equals(dimsEnglish[ii+1])) euIndexNext = ii+1;
                    break;
                }
            }
 
            // System.out.println("englishVal before units: " +englishVal);
            
            
            // now we need to find an appropriate scale and units for the
            // value we are using
            
            while (euIndex < euIndexNext && englishVal >= engeng[euIndexNext]*.5) {
                euIndex = euIndexNext;
                if (euIndex < unitsEnglish.length-1
                    && targetdim.equals(dimsEnglish[euIndex+1])) euIndexNext++;
            }
            englishVal /= engeng[euIndex];
            unitsEng.setSelectedIndex(euIndex);
            
            
            englishScale = scales[scales.length-1];
            int englishScaleIndex = scales.length-1;
            
            // System.out.println("englishVal before scaling: " +englishVal);
            
            for (int ii = scales.length-1; ii >= 0; ii--) {
                if (englishVal < scales[ii]*9.99999) {
                    englishScale = scales[ii];
                    englishVal = englishVal/englishScale;
                    englishScaleIndex = ii;                    
                    break;
                }
                
            }

            // System.out.println("englishVal after scaling: " +englishVal);

            scaleEng.setSelectedIndex(englishScaleIndex);
            valEng.setText(Double.toString(englishVal));
        }catch (NumberFormatException nfe) {
            valMet.setText("Please enter a valid number: " + nfe.getMessage());
        }
    }
    

    
    public metconv()  //default constructor
    {
        //System.out.println("creating units conversion object");
    }
    
    public void init()  // to call on load (once)
    {
        // System.out.println("initializing units conversion applet");
        Container outerpane=getContentPane();  // The ContentPane is the
                                           // place where we add all the
                                           // components of the applet
        apppanel = new appPanel();  // starting with a panel 
                                           // that has within it eveything
                                           // we will draw
        outerpane.add(apppanel);
    }
    
    public void start() // to call after load
    {
        // System.out.println("units conversion applet starting");
        
    }
    
    public void stop() // to call at the end
    {
        // System.out.println("units conversion applet stopping");
    }
    
    public void destroy() // to call on exit
    {
    }
    
    public class appPanel extends JPanel  // this is where we really do
                                          // the drawing for the applet
    {
        public appPanel() //applet panel object
        {
            this.setBackground(Color.cyan);
            this.setLayout(new FlowLayout());
            this.add(new JLabel("Enter English value, scale, units :"));
            valEng = new JTextField("?",20);
            this.add(valEng);
            scaleEng = new JComboBox(prefixes);
            scaleEng.setSelectedIndex(10);
            unitsEng = new JComboBox(unitsEnglish);
            this.add(scaleEng);
            this.add(unitsEng);
            this.add(new JLabel("Enter Metric value, scale, units :"));
            valMet = new JTextField("?",20);
            this.add(valMet);
            scaleMet = new JComboBox(prefixes);
            scaleMet.setSelectedIndex(10);
            unitsMet = new JComboBox(unitsMetric);
            this.add(scaleMet);
            this.add(unitsMet);
            this.add(new JLabel("Type a new value and press enter to update"));



            // When changes are made to valEng compute valMet, scaleMet, unitsMet
            valEng.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e){
                                     System.out.println("valEng action listener");
                                     updateMetric();
              }
            });
            // When changes are made to tempC compute tempF
            valMet.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e){
                                     System.out.println("valMet action listener");
               updateEnglish();
               }
            });

        }
    }
    
    // This is the main program to convert the applet to
    // an application
    
    public static void main(String args[]) {
        JFrame DrawingFrame = new JFrame("Temperature Conversions");  //Make the frame
        DrawingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //Be sure is closes on exit
        metconv applet = new metconv();                               //Make an applet instance
        DrawingFrame.setContentPane(applet);                          //Give this frame to the applet
        applet.init();                                                //Initialize the applet
        DrawingFrame.setSize(350,250);                                //Set the frame size
        DrawingFrame.setVisible(true);                                //Make the frame visible
        applet.start();                                               //If the applet has start logic
                                                                      //run it
        
    }

}