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;  

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){

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){
                        //Place the selected rates group in the drop down combobox
                        for(Object o:rates.get(index))
                        //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

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>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"));
                                    if(!checkBlank(txtLeft,txtRight, cbrates))
                                                if(txtRight.getText().equals("")){ //left to right conversion
                                                            number = format.parse(txtLeft.getText());            
                                                            double leftAmount=number.doubleValue();                                          
                                                            String rightAmount=leftToRight(rate,leftAmount);

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

45 public void showResult(JTextField txtres, String amount, JTextField txtfrom){

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))

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"); 

            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();

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.

Saturday, April 27, 2013

Currency Conversion program

This is a simple currency conversion program. The program allows you to convert from USD amount to Riel amount and vise versa and from EURO amount to USD amount and vise versa. In this program, you will learn to use  the JTabbedPane class, and JComboBox lass, and to write Java code to detect key typed.

CurrencyConversion source code:

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

class  CurrencyConversion extends JFrame implements ActionListener{
            JTabbedPane tbpane;
            JPanel panelt1;
            JLabel lblus;
            JLabel lblkh;
            JLabel lblcbkh;
            JTextField txtus;
            JTextField txtkh;
            JComboBox cbratekh;
            JButton btuskh;
            JPanel panelt2;
            JLabel lbleuro;
            JLabel lbleurous;
            JLabel lblcbus;
            JTextField txteurous;
            JTextField txteuro;
            JComboBox cbrateus;
            JButton bteurous;   

1                      setTitle("Currency Conversion Program");
2                      setDefaultCloseOperation(EXIT_ON_CLOSE);
3                      setSize(300,250);
4                      setResizable(false);
5                      Container cont=getContentPane();

                        //USD to Riel conversion interface
6                      lblus=new JLabel("USD:");
7                      lblkh=new JLabel("Riel:");
8                      lblcbkh=new JLabel("Select exchange rate:");
9                      btuskh=new JButton("OK");
10                    btuskh.addActionListener(this);               
11                    txtus=new JTextField(10);
12                    txtus.addKeyListener(new KeyList());
13                    txtkh=new JTextField(10);
14                    txtkh.addKeyListener(new KeyList());
15                    Object[] ratekh={3800,3900,4000,4100,4200};
16                    cbratekh=new JComboBox(ratekh);
17                    cbratekh.setEditable(true);
18                    cbratekh.getEditor().getEditorComponent().addKeyListener(new KeyList());
19                    panelt1=new JPanel();
20                    panelt1.add(lblcbkh);
21                    panelt1.add(cbratekh);
22                    panelt1.add(lblus);
23                    panelt1.add(txtus);
24                    panelt1.add(lblkh);
25                    panelt1.add(txtkh);
26                    panelt1.add(btuskh);
27                    panelt1.setLayout(new GridLayout(4,1));
                        //EURO and USD conversion interface
28                    lbleuro=new JLabel("Euro:");
29                    lbleurous=new JLabel("USD:");
30                    lblcbus=new JLabel("Select exchange rate:");
31                    bteurous=new JButton("OK");
32                    bteurous.addActionListener(this);                       
33                    txteuro=new JTextField(10);
34                    txteuro.addKeyListener(new KeyList());
35                    txteurous=new JTextField(10);
36                    txteurous.addKeyListener(new KeyList());
37                    Object[] rateus={1.25,1.28,1.30,1.32,1.35,1.40};
38                    cbrateus=new JComboBox(rateus);
39                    cbrateus.setEditable(true);
40                    cbrateus.getEditor().getEditorComponent().addKeyListener(new KeyList());
41                    panelt2=new JPanel();
42                    panelt2.setLayout(new GridLayout(4,1));
43                    panelt2.add(lblcbus);
44                    panelt2.add(cbrateus);
45                    panelt2.add(lbleuro);
46                    panelt2.add(txteuro);
47                    panelt2.add(lbleurous);
48                    panelt2.add(txteurous);
49                    panelt2.add(bteurous);
                        //Create JTabbedPane object and add panelt1 and panelt2
50                    JTabbedPane tbpane=new JTabbedPane();
51                    tbpane.add(panelt1, null, 0);
52                    tbpane.add(panelt2, null, 1);
                        //Set title to each tab
53                    tbpane.setTitleAt(0,"USD and Riel");
54                    tbpane.setTitleAt(1,"EURO and USD");

                        //Add tbpane JTabbedPane object to the container
55                    cont.add(tbpane);
56                    setVisible(true);                   

57 public void actionPerformed(ActionEvent e){
                        double rate;
                        double usdamount;
                        double khamount;
                        double euroamount;
                                    if(!checkBlank(txtus,txtkh, cbratekh))
                                                if(txtkh.getText().equals("")){ //USD to Riel conversion

                                                else if(txtus.getText().equals("")) { //Riel to USD conversion
                                                showMessage("Please leave the result text box blank");
                        else if(e.getSource()==bteurous){
                                    if(!checkBlank(txteurous,txteuro, cbrateus))
                                                if(txteurous.getText().equals("")){ //Euro to USD conversion

                                                else if(txteuro.getText().equals("")) { // USD to EURO conversion
                                                showMessage("Please leave the result text box blank");

Currency Conversion program in Java

Code Explanation:
1 Set the title of the program window (Currency Conversion Program).
2 Let the program window close when the user clicks the close button.
3 Specify the width and height of the program window when it opens.
4 Disable program window resizing.
5 Create a container object to act as the controls placeholder.
6-27 Construct the interface for USD and Riel conversion. We need three labels, one combobox, two text boxes, and one button. These controls are grouped together in the panelt1 object. The combobox allows the user to select conversion rate. The text boxes are for inputting USD or Riel  amount. Inputting in both text boxes in one operation is not valid. If you input USD, the conversion will be made from USD currency to Riel  currency and vise versa. The two text boxed are registered to the key event so that restriction can be placed on its key typed. The button object is registered to the action event to enable button-click action.
28-49 The construction of  the interface for EURO and USD conversion is done in the same way as the interface for USD and Riel  conversion except different names of controls.
50 Create a JTabbedPane object tbpane.
51 Place the panelt1 to the first tab.
52 Place the panelt2 tot the second tab.
53 Set title of the first tab to "USD and Riel " text.
54 Set title of the second tab to "EURO and USD" text.
55 Add the tbpane oject to the container.
56 Make user the program window is visible.
57 The actionPerformed method is rewritten to enable the button-click action. When the user clicks btuskh from the first tab, the conversion is made from USD amount to Riel  amount or vise versa. If you want to convert from USD to Riel , input the USA amount and leave the Riel  text box blank and vise versa.
If the user clicks the bteurous button from the second tab, the conversion is for EURO to USA currency. It works the same way as the previous button click except for different currencies conversion.
 58 The KeyList class extends the KeyAdapter class to rewrite the keyTyped method. This method defines code to restrict key typed in all text boxes. Only number, dot, backspace, and delete keys are accepted.
59 The checkBlank method is implemented to check whether the combobox conversion rate or the two text boxes are not blank before conversion can be made.
60 The usdToKH method is invoked to convert from USD amount to Riel  amount.
61 The khToUSD method is invoked to convert from Riel  amount to USD amount.
62 The euroToUSD method is invoked to convert from EURO amount to USD amount.
63 The usdToEURO method is invoked to convert from USD amount to EURO amount.
65 The showMessage method is invoked to show a message dialog to inform the user when an invalid action is being made.
66 The CurrencyConversion Program has the main method to start the program.