Monday, April 29, 2013

Currency Exchange Calculator

The Currency Exchange Calculator program extends the ability of the previous Currency Conversion program. The currency Exchange Calculator allows you to exchange or convert many currency types in a single form.

CurrencyExchangeCalculator source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class  Exchange extends JFrame implements ActionListener{
            JPanel panel;
            JLabel lblLeft;
            JLabel lblRight;
            JLabel lblrate;
            JLabel lblcbLeftRight;
            JTextField txtLeft;
            JTextField txtRight;
            JComboBox cbrates;
            JComboBox cbLeftRight;
            JButton btConvert;  
           

            Exchange(){
1                      setTitle("Currency Exchange Calculator");
2                      setSize(500,250);
3                      setResizable(false);
4                      setLayout(new FlowLayout());
5                      setLocationRelativeTo(null);
6                      setDefaultCloseOperation(EXIT_ON_CLOSE);
7                      Container cont=getContentPane();
8                      lblcbLeftRight=new JLabel("Select currency:");
9                      lblLeft=new JLabel("From:");
10                    lblRight=new JLabel("To:");
11                    lblrate=new JLabel("Select exchange rate:");
12                    btConvert=new JButton("OK");
13                    btConvert.addActionListener(this);
14                    txtLeft=new JTextField(12);
15                    txtLeft.addKeyListener(new KeyList());   
16                    txtRight=new JTextField(12);
17                    txtRight.addKeyListener(new KeyList());
18                    cbrates=new JComboBox();
19                    cbrates.setEditable(true);
20                    cbrates.getEditor().getEditorComponent().addKeyListener(new KeyList());
21                    initializeRates()
22                    cbLeftRight=new JComboBox();
23                    cbLeftRight.addItemListener(new ItemListener(){
                                    public void itemStateChanged(ItemEvent e){
                                                setRate(cbLeftRight.getSelectedIndex(),cbLeftRight.getSelectedItem().toString
());
                                    }
                        });

24                    initializeCurPair();

25                    panel=new JPanel();
26                    panel.setLayout(new GridLayout(5,2));
27                    panel.add(lblcbLeftRight);
28                    panel.add(cbLeftRight);
29                    panel.add(lblrate);                           
30                    panel.add(cbrates);
31                    panel.add(lblLeft);                           
32                    panel.add(txtLeft);
33                    panel.add(lblRight);            
34                    panel.add(txtRight);
35                    panel.add(btConvert);
36                    cont.add(panel);
37                    JLabel lbldes=new JLabel("<html>"+getDes()+"</html>");
38                    cont.add(lbldes);
39                    setVisible(true);       
                                   
                       
            }


40 public void setRate(int index,String text){
                        cbrates.removeAllItems();
                       
                        //Place the selected rates group in the drop down combobox
                        for(Object o:rates.get(index))
                                    cbrates.addItem(o);
                        //Set labels
                        String[] cur=text.split("-");
                        lblLeft.setText(cur[0]+" amount:");
                        lblRight.setText(cur[1]+" amount:");
            }
41 public void initializeRates(){
            rates=new HashMap<Integer,Object[]>();
            //initialize exchange rates             
                        Object[] rateAUD_CAD={1.044,1.047,1.052,1.054,1.059};
                        Object[] rateAUD_CHF={0.972,0.974,0.976,0.977,0.980};
                        Object[] rateAUD_CNY={6.410,6.412,6.415,6.417,6.420};
                        Object[] rateAUD_EUR={0.785,0.787,0.790,0.791,0.793};
                        Object[] rateAUD_GBP={0.64,0.66,0.67,0.68,0.70};
                        Object[] rateAUD_JPY={102.354,102.357,102.359,102.400,102.410};
                        Object[] rateAUD_NZD={1.10,1.15,1.20,1.21,1.25,1.27};
                        Object[] rateAUD_USD={1.010,1.021,1.031,1.032,1.034,1.037};
                        Object[] rateCAD_CHF={0.918,0.920,0.922,0.925,0.928};
                Object[] rateCAD_CNY={6.070,6.075,6.080,6.088,6.090};
                        Object[] rateCAD_EUR={0.60,0.75,0.80,0.85,0.90};
                        Object[] rateCAD_GBP={0.620,0.625,0.636,0.638,0.641};
                        Object[] rateCAD_JPY={97.120,97.132,97.142,97.145,97.150};
                        Object[] rateCAD_NZD={1.130,1.138,1.148,1.155,1.160,1.165};
                        Object[] rateCAD_USD={0.960,0.970,0.978,0.980,0.985,0.990};
                        Object[] rateCHF_CNY={6.570,6.575,6.584,6.589,6.595};
                        Object[] rateCHF_EUR={0.809,0.811,0.813,0.815,0.820};
                        Object[] rateCHF_GBP={0.678,0.682,0.688,0.690,0.693};
                        Object[] rateCHF_JPY={105.040,105.045,105.053,105.058,105.062};
                        Object[] rateCHF_NZD={1.231,1.241,1.245,1.248,1.250,1.255};
                        Object[] rateCHF_USD={1.040,1.048,1.050,1.053,1.058,1.062};
                        Object[] rateCNY_EUR={0.119,0.121,0.123,0.125,0.127};
                        Object[] rateCNY_GBP={0.100,0.102,0.104,0.106,0.108};
                        Object[] rateCNY_JPY={15.940,15.947,15.957,15.960,15.967};
                        Object[] rateCNY_NZD={0.184,0.187,0.189,0.201,0.205};
                        Object[] rateCNY_USD={0.151,0.157,0.161,0.165,0.167};
                        Object[] rateEUR_GBP={0.840,0.845,0.848,0.851,0.853};
                        Object[] rateEUR_JPY={129.462,129.467,129.467,129.469,129.471};
                        Object[] rateEUR_NZD={1.47,1.49,1.53,1.55,1.57};
                        Object[] rateEUR_USD={1.209,1.301,1.303,1.305,1.307};
                        Object[] rateGBP_JPY={152.714,152.717,152.719,152.721,152.723};
                        Object[] rateGBP_NZD={1.801,1.803,1.805,1.807,1.809};
                        Object[] rateGBP_USD={1.533,1.538,1.539,1.541,1.543};
                        Object[] rateJPY_NZD={0.009,0.010,0.011,0.012,0.013};
                        Object[] rateJPY_USD={0.01,0.02,0.03,0.04,0.05};
                        Object[] rateNZD_USD={0.847,0.852,0.857,0.861,0.863};
                        Object[] rateUSD_Riel={3800,3900,4000,4100,4200};
                       
                                               
                        //Put exchanges in the HashMap object
                        rates.put(0,rateAUD_CAD);
                        rates.put(1,rateAUD_CHF);
                        rates.put(2,rateAUD_CNY);
                        rates.put(3,rateAUD_EUR);
                        rates.put(4,rateAUD_GBP);
                        rates.put(5,rateAUD_JPY);            
                        rates.put(6,rateAUD_NZD);
                        rates.put(7,rateAUD_USD);          
                        rates.put(8,rateCAD_CHF);
                        rates.put(9,rateCAD_CNY);                      
                        rates.put(10,rateCAD_EUR);
                        rates.put(11,rateCAD_GBP);                    
                        rates.put(12,rateCAD_JPY);
                        rates.put(13,rateCAD_NZD);                    
                        rates.put(14,rateCAD_USD);
                        rates.put(15,rateCHF_CNY);                    
                        rates.put(16,rateCHF_EUR);
                        rates.put(17,rateCHF_GBP);         
                        rates.put(18,rateCHF_JPY);                      
                        rates.put(19,rateCHF_NZD);
                        rates.put(20,rateCHF_USD);                    
                        rates.put(21,rateCNY_EUR);
                        rates.put(22,rateCNY_GBP);                    
                        rates.put(23,rateCNY_JPY);
                        rates.put(24,rateCNY_NZD);                    
                        rates.put(25,rateCNY_USD);                    
                        rates.put(26,rateEUR_GBP);                    
                        rates.put(27,rateEUR_JPY);                     
                        rates.put(28,rateEUR_NZD);                    
                        rates.put(29,rateEUR_USD);                    
                        rates.put(30,rateGBP_JPY);                      
                        rates.put(31,rateGBP_NZD);                     
                        rates.put(32,rateGBP_USD);
                        rates.put(33,rateJPY_NZD);                      
                        rates.put(34,rateJPY_USD);
                        rates.put(35,rateNZD_USD);        
                        rates.put(36,rateUSD_Riel);
                       
            }

42 public void initializeCurPair(){
                        cbLeftRight.addItem(new String("AUD-CAD"));
                        cbLeftRight.addItem(new String("AUD-CHF"));
                        cbLeftRight.addItem(new String("AUD-CNY"));
                        cbLeftRight.addItem(new String("AUD-EUR"));
                        cbLeftRight.addItem(new String("AUD-GBP"));
                        cbLeftRight.addItem(new String("AUD-JPY"));
                        cbLeftRight.addItem(new String("AUD-NZD"));
                        cbLeftRight.addItem(new String("AUD-USD"));

                        cbLeftRight.addItem(new String("CAD-CHF"));
                        cbLeftRight.addItem(new String("CAD-CNY"));
                        cbLeftRight.addItem(new String("CAD-EUR"));
                        cbLeftRight.addItem(new String("CAD-GBP"));
                        cbLeftRight.addItem(new String("CAD-JPY"));
                        cbLeftRight.addItem(new String("CAD-NZD"));
                        cbLeftRight.addItem(new String("CAD-USD"));

                        cbLeftRight.addItem(new String("CHF-CNY"));
                        cbLeftRight.addItem(new String("CHF-EUR"));
                        cbLeftRight.addItem(new String("CHF-GBP"));
                        cbLeftRight.addItem(new String("CHF-JPY"));
                        cbLeftRight.addItem(new String("CHF-NZD"));
                        cbLeftRight.addItem(new String("CHF-USD"));

                        cbLeftRight.addItem(new String("CNY-EUR"));
                        cbLeftRight.addItem(new String("CNY-GBP"));
                        cbLeftRight.addItem(new String("CNY-JPY"));
                        cbLeftRight.addItem(new String("CNY-NZD"));
                        cbLeftRight.addItem(new String("CNY-USD"));

                        cbLeftRight.addItem(new String("EUR-GBP"));
                        cbLeftRight.addItem(new String("EUR-JPY"));
                        cbLeftRight.addItem(new String("EUR-NZD"));
                        cbLeftRight.addItem(new String("EUR-USD"));

                        cbLeftRight.addItem(new String("GBP-JPY"));
                        cbLeftRight.addItem(new String("GBP-NZD"));
                        cbLeftRight.addItem(new String("GBP-USD"));

                        cbLeftRight.addItem(new String("JPY-NZD"));
                        cbLeftRight.addItem(new String("JPY-USD"));

                        cbLeftRight.addItem(new String("NZD-USD"));
                        cbLeftRight.addItem(new String("USD-Riel"));
                       
            }

43 public String getDes(){
                        String des="<p>AUD=Australian Dollar</p>";
                        des+="<p>CAD=Canadian Dollar</p>";
                        des+="<p>CHF=Swiss Franc</p>";
                        des+="<p>CNY=Chinese Yuan</p>";
                        des+="<p>EUR=Euro</p>";
                        des+="<p>GBP=Britis Pound</p>";
                        des+="<p>JPY=Japanese Yen</p>";
                        des+="<p>NZD=New Zealand Dollar</p>";
                        des+="<p>Riel=Cambodian Riel</p>";
                        des+="<p>USD=United States Dollar</p>";
                        return des;
        }
44 public void actionPerformed(ActionEvent e){
                        double rate;
                        Number number;
                        NumberFormat format = NumberFormat.getInstance(new Locale("Locale.US"));
                        try{
                        if(e.getSource()==btConvert){
                                    if(!checkBlank(txtLeft,txtRight, cbrates))
                                                if(txtRight.getText().equals("")){ //left to right conversion
                                                            rate=Double.parseDouble(cbrates.getSelectedItem().toString());
                                                            number = format.parse(txtLeft.getText());            
                                                            double leftAmount=number.doubleValue();                                          
                                                            String rightAmount=leftToRight(rate,leftAmount);
                                                            showResult(txtRight,rightAmount,txtLeft);  
                                                }

                                                else if(txtLeft.getText().equals("")) {//right to left conversion
                                                            rate=Double.parseDouble(cbrates.getSelectedItem().toString());
                                                            number = format.parse(txtRight.getText());                     
                                                            double rightAmount=number.doubleValue();                                       
                                                            String  leftAmount=rightToLeft(rate,rightAmount);
                                                            showResult(txtLeft,leftAmount,txtRight);
                                                }
                                                else{
                                                            showMessage("Please leave the result text box blank");
                                                }
                                               
                                    }
                        }catch(ParseException pe){}
            }

45 public void showResult(JTextField txtres, String amount, JTextField txtfrom){
           txtres.setText(amount);
           txtres.setForeground(Color.RED);
           txtfrom.setForeground(Color.BLACK);
               
        }

46 public class KeyList extends KeyAdapter{
            public void keyTyped(KeyEvent ke){
           
                        char c = ke.getKeyChar();
                        int intkey=(int)c;
                        if(!(intkey>=48 && intkey<=57 || intkey==46 || intkey==8 || intkey==127))
                         {
                                    ke.consume();
                        }
            }
}

46 public boolean checkBlank(JTextField txtLeft,JTextField txtRight, JComboBox cb){
            boolean bl=false;
            if((txtLeft.getText().equals("") && txtRight.getText().equals("") ) || cb.getSelectedItem().toString().equals
("")){
            showMessage("Don't leave all text boxes or drop down list blank"); 
            bl=true;
                        }

            return bl;
            }


47 public String leftToRight(double rate, double leftAmount){
                       
                        return getFormatedValue(leftAmount*rate);
            }

48 public String rightToLeft(double rate, double rightAmount){
                        return getFormatedValue(rightAmount/rate);
            }

49 public String getFormatedValue(double value){
                        DecimalFormat df=new DecimalFormat("#,###.000");
                        return df.format(value);
            }

50 public void showMessage(String message){
           
            JOptionPane dialog=new JOptionPane();
            dialog.showMessageDialog(this,message,"Error",JOptionPane.ERROR_MESSAGE);
            }
}

51 public class CurrencyExchangeCalculator{
 
            public static void main(String args[]){
                        new Exchange();
  
            }


}

Currency Exchange Calculator in Java



Code Explanation:
1 Set the title of the program window (Currency Exchange Calculator).
2 Specify the width and height of the program window when it opens.
3 Disable program window resizing.
4 Specify the layout of the program window. The FlowLayout make the controls on the window flown from the left to right and downward.
5 Display the program widow at the center of the screen.
6 Let the program window close when the user clicks the close button.
7 Create a container object to act as the controls placeholder.
8 Create a JLabel lblcbLefRight to display the text "Select currency:".
9 Create a JLabel lblLeft to display the text of the left currency from the currency pair selected from the combobox. For example, if you select AUD-CAD from combobox, the lblLeft label displays "AUD" text.
10 Create a JLabel lblRight to display the text of the right currency from the currency pair selected from the
combobox. For example, if you select AUD-CAD from combobox, the lblRight label displays "CAD" text.
11 Create a JLabel lblrate to display the text "Select exchange rate:".
12 Create a JButton btConvert object. It is clicked to exchange or convert from one currency amount to another currency amount.
13 The btConvert button is registered with the action event so that the actionPerformed of the ActionLister interface can be overriden to enable the button action.
14-15 The JTextField txtLeft is created and registered with key event so that you can write code in the keyPressed method of the KeyAdapter class to detect the key input. The txtLeft textbox allows the user to input or edit the amount of the left currency. If you input the amount in the txtLeft textbox and leave the txtRight textbox blank, the exchange is from the left currency to the right currency. So the result is placed in the txtRight textbox.
16-17 Create the JTextField txtRight textbox. This textbox works similarly to txtLeft textbox mentioned above except it is for inputting or editing the right currency amount.
18-20 Create the JComboBox cbrates. This combobox is to store the exchange rates of the currency pair selected.
To provide more flexibility, the combobox is editable. If the rates provided in the combobox drop down list do not meet the need of the user, he/she can enter his/her own rate.
21 The initializeRates method is invoked to store a list of exchange rates in the HashMap rates object. Each group of exchange rates for one currency pair is stored in an Object array. This array is added to HashMap rates object by using the put method.
The first group is stored at index 0, second group at index 1 and so on.
22-23 The JComboBox cbLeftRight is created to store a list of currency pairs. When a currency pair selected from the cbLeftRight combobox the setRate method is invoked to place the exchanged rates of the selected currency pair in the cbrates combobox.
24 The initializeCurPair is invoked to place all currency pairs in the cbLeftRight combobox.
25-35 Create a JPanel panel object and place all object controls mentioned above in it.
36 Add the panel object to the container.
37 Create a JLabel lbldes object to show the currency abbreviations and their long forms.
38 Add the lbldes to the container.
39 Make use the program window visible.
40 The setRate method is invoked when an currency pair of the cbLeftRight combobox is selected. The group of exchange rates for the selected currency pair is populated in the cbrates combobox and the lblLeft and lblRight labels change their values. The lblLeft takes the left currency and the lblRight takes the right currency.
41 The initializeRates method has code to store the list of excchange rates in the HashMap rates object.
42 The initializeCurPair method has code to store the list of currency pair in the cbLeftRight combobox.
43 The getDes method is written to display the currency abbreviations and their long form on the lbldes label.
44 The actionPerformed method is rewritten to enable the button-click action so that the conversion from the left to the right currencies can be performed. When the OK button is clicked, the first thing to do is checking whether the user leave all textboxes or cbrates combobox blank. In this program, we use the NumberFormat class to format the string amount that contains thousand separator (,) so the double type of the amount (with thousand separator) can be obtain without any problem.
45 The showResult method is invoked in the actionPeform method to display the result of the conversion. The result amount is displayed in red color.
46 The KeyList class rewrites the keyTyped method of the KeyAdapter class. This method has code to restrict key typed in all text boxes. Only number, dot, backspace, and delete keys are accepted.
47 The leftToRight method is implemented to exchange or convert from the left currency to the right currency.
48 The rightToLeft method is implemented to exchange or convert from the right currency to the left currency.
49 The getFormattedValue method is invoked by the leftToRight and rightToLeft method. It uses the DecimalFormat class to format the result amount. The result amount includes thousand separator and has three decimal places.
50  The showMessage method is invoked to show a message dialog to inform the user about incorrect action by leaving all textboxes, or  cbrates blank, or by entering amounts all textboxes. One textbox (to display the result amount)  among the two textboxes must be blank.

9 comments:

  1. The calculation of time plays a vital role for getting the 100% work form the employee by avoiding their waste activities. The Time Card Calculator is usually used for calculating the time of the companies employee and their all activities which they have done in a working hours.

    ReplyDelete
  2. Additionally, Forex markets have given most currency pairs nicknames or abbreviations, which reference the pair rather than necessarily anyone currencies involved.
    bitcoinvest.cc

    ReplyDelete
  3. For a long time me & my friend were searching for informative blogs, but now I am on the right place guys, you have made a room in my heart! 90%+ Accuracy on all VIP trades.

    ReplyDelete
  4. The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. penny stocks

    ReplyDelete
  5. There are a lot of blogs and articles out there on this topic, but you have acquired another side of the subject. This is reliable content thank you for sharing it. Netflix stock falls short

    ReplyDelete
  6. If you are looking for a truly accurate currency converter, you can use this Websitecalculator, its one of the best.<a

    ReplyDelete
  7. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now,20 euros to dollars and I really like your style. Thanks a million and please keep up the effective work.

    ReplyDelete