Start Search Contents Index Links About
ExchangeRateCalculator.java
/*
 * Author: Havard Rast Blok
 * E-mail: 
 * Web   : www.rememberjava.com
 */

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

/**
 * Reads a web page and extracts exchange rate information.
 * This information is used in a simple calculator.
 
 * It is designed for the "Aftenposten valutakurser" web page:
 * http://www.aftenposten.no/nyheter/okonomi/
 * However, it should be fairly easy to adjust to other's.
 
 * IMPORTANT!
 * Aftenposten is a registered tradmark, and this program
 * is for educational purposes only.
 */
public class ExchangeRateCalculator extends JFrame implements ItemListener, KeyListener
{
  //parsing information (from the week 48-2001 program)
  private final String startRates = "<table width=100%>";
  private final String startInfo = "sans-serif\">";
  private final String endInfo ="</font";
  private final String endRates = "</TABLE>";
  private final int currencies = 20;

  //GUI
  private Container c;
  private JLabel localLabel;
  private JTextField localText, foreignText;
  private JComboBox currency;
  
  private float rate;
  private String currencyNames[];
  private float rates[];

  public ExchangeRateCalculatorURL theURL )
  {
    super"Exchange Rate Calculator" );
    
    //load exchange rates
    loadRatestheURL );
    
    //set up GUI
    
    setSize(250150);
    c = getContentPane();
    c.setLayoutnew GridLayout2) );
   
    localLabel = new JLabel"Local currency" );
    localText = new JTextField();
    localText.addKeyListenerthis );
    foreignText = new JTextField();
    foreignText.addKeyListenerthis );
    currency = new JComboBoxcurrencyNames );
    currency.addItemListenerthis );
    
    c.addlocalLabel );
    c.addlocalText );
    c.addcurrency );
    c.addforeignText );
    
    //update current rate by faking selection
    itemStateChanged(null);
    
    pack();
    show();
  }
  
  /**
   * Update the local currency text field based upon the value
   * in the foreign text field.
   */
  private void updateLocal()
  {
    float value;
    
    try
    {
      value = Float.parseFloatforeignText.getText() );
      localText.setText"" (value*rate) );
    }
    catch(NumberFormatException e)
    {
      System.out.println("ExchangeRateCalculator.updateLocal - error parsing: "+e);
    }

  }

  /**
   * Update the foreign currency text field based upon the value
   * in the local text field.
   */
  private void updateForegin()
  {
    float value;
    
    try
    {
      value = Float.parseFloatlocalText.getText() );
      foreignText.setText"" (value*rate) );
    }
    catch(NumberFormatException e)
    {
      System.out.println("ExchangeRateCalculator.updateForegin - error parsing: "+e);
    }
   
  }
  
  public void keyTypedKeyEvent e )
  {
    //System.out.println("keyTyped");
  }
  
  public void keyPressed(KeyEvent e)
  {
    //System.out.println("keyPressed");
  }

  /**
   * Detect a change in the text field and
   * change the calulated value.
   */
  public void keyReleased(KeyEvent e)
  {
    //System.out.println("keyReleased");
  
    Object source = e.getSource();
    
    ifsource == localText )
    {
      updateForegin();
    }
    else ifsource == foreignText )
    {
      updateLocal();
    }

  }

  /**
   * Sets the current rate based upon the selected
   * country from the list.
   */
  public void itemStateChanged(ItemEvent e)
  {
    int index = currency.getSelectedIndex();
    rate = rates[index];
    localText.setText("0.0");
    foreignText.setText("0.0");
  }
  
  /**
  * Load the exchange rates from web (or a local file)
  * (from the week 48-2001 program)
  @param theURL web or local URL for the file
  */
  public void loadRatesURL theURL )
  {
    BufferedReader bufReader;
    String line;
    boolean foundRates;
    int startInfoLength;
    int infoIndex;
    int endIndex;
    String infoString;
    boolean done;
    int colCounter;
    int rowCounter;
    String info[][];
    
    //init variables
    foundRates = false;
    done = false;
    startInfoLength = startInfo.length();
    colCounter = 0;
    rowCounter = 0;
    info = new String[currencies][4];
    
    currencyNames = new String[currencies];
    rates = new float[currencies];
    
    try
    {
      //open web page
      bufReader = new BufferedReadernew InputStreamReader(theURL.openStream()) );
      
      //read line by line
      while( (line = bufReader.readLine()) != null && !done )
      {
        //System.out.println(line);
      
        //check if the exchange rate table is found
        if!foundRates )
        {
          //if not, check if it starts in this line
          foundRates = (line.indexOf(startRates!= -1);
        }
        //check if this line contains interesing information
        else if( ( infoIndex = line.indexOf(startInfo)) != -)
        {
          //if it does, check if it is of the first four coloumns
          //(The 5th is yesterday's news...)
          ifcolCounter < )
          {
            //extract the information
            //(no number conversion is done here)
            endIndex = line.indexOf(endInfo);
            infoString = line.substringinfoIndex + startInfoLength, endIndex );
            
            //put it in a 2d array
            info[rowCounter][colCounter= infoString;
            colCounter++;
          }
          else
          {
            //end of row (both on web page and in array)
            rowCounter++;
            colCounter = 0;
          }
        }
        //check if exchange rate table is finished
        else ifline.indexOfendRates != -)
        {
          done = true;
        }
      }
      
      //close the file when finished
      bufReader.close();
    }
    catchIOException e )
    {
      System.out.println"ShowRate.ShowRate - error opening or reading URL: " + e );
    }
    
    //Extract names and calclate real rate (by 1 unit, not 100 or 1000)
    for(int i = 0; i < currencies; i++)
    {
      currencyNames[i= info[i][1" - " + info[i][2];
      rates[i= Float.parseFloatinfo[i][0] ) * Float.parseFloatinfo[i][3] );
    }
  }
  
  public static void mainString args[] )
  {
    try
    {
      new ExchangeRateCalculatornew URL"http://www.aftenposten.no/nyheter/okonomi/article.jhtml?articleID=34015&vistype=valutakurser" ) );
      
      //Open web page
      //new ExchangeRateCalculator(new URL(args[0]));
      
      //Open from local file
      //File f = new File( args[0] );
      //new ExchangeRateCalculator( f.toURL() );
    }
    catch (MalformedURLException e)
    {
      System.out.println("ExchangeRateCalculator.main - wrong url: " +e );
    }
    
  }
}


site: Håvard Rast Blok
mail:
updated: 27 July 2007