Clicky

Can anybody help me with this project. I am trying to let this program read from XML file.  Data online on this web: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml. How to make this project pull the information from that web and put it txt file then appear it on the GUI. This what I have done and I still have error.
 /*  * To change this template, choose Tools | Templates  * and open the template in the editor.  */  /*  * Converter.java  *  * Created on Dec 1, 2011, 8:06:24 PM  */ package Converter;  import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComboBox; import javax.swing.JFormattedTextField;    /**  *  * @author Abdullah  */ public class Converter extends javax.swing.JFrame {      /** Creates new form Converter */      String currentPattern;     private HashMap<String, Double> HashMap1;     private ArrayList<String> List;                                                      private ArrayList<String> currencies;;     private Converter cc; DecimalFormat df = new DecimalFormat("#####.00");      /** Creates new form Converter */      public Converter() throws Exception{     initComponents();  HashMap1= new HashMap<String, Double>(); List = new ArrayList<String>(); try{  URL ecb = new url.("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"); BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream())); FileWriter fw = new FileWriter("Rates.xml"); String inputLine;   while ((inputLine = in.readLine()) != null){ System.out.println(inputLine); fw.write(inputLine); }  in.close(); fw.close(); } catch(Exception e){ System.exit(1); }                        /** Creates new form CurrencyConverterGUI */       //   initComponents();         String[] patternExamples = {"EUR", "USD"};           HashMap1 = new HashMap<String, Double>();         List = new ArrayList<String>();         currencies = new ArrayList<String>();          populateHashMap();                   CurrencyBox1.removeAll();          CurrencyBox2.removeAll();          for(String s: currencies){               CurrencyBox1.addItem(s);                   CurrencyBox2.addItem(s);           }                CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 CurrencyBox1ActionPerformed(evt);             }         });                CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 CurrencyBox2ActionPerformed(evt);             }         });          /*         currentPattern = patternExamples[0];         for(int j=0; j<patternExamples.length; j++){         CurrencyBox1.addItem(patternExamples[j]);           CurrencyBox2.addItem(patternExamples[j]);}         */         CurrencyBox1.setEditable(false);              CurrencyBox2.setEditable(false);          //CurrencyBox1.addActionListener(this);     }      private void populateHashMap() {         Scanner SC = null;         try {              SC = new Scanner(new FileReader(new File("Rates.txt")));         } catch (IOException e) {             System.err.println("File Error when reading rates.txt file");             //return;             System.exit(1);         }         while (SC.hasNextLine()) {             String[] S = SC.nextLine().split(" ");             currencies.add(S[0]);             HashMap1.put(S[0], Double.valueOf(S[1]));             }     } public Object[] getCurrencies() { 		return List.toArray(); 	}  	public double convert(String FC, String TC, double amt) {  	double result = amt / HashMap1.get(FC) * HashMap1.get(TC); 		return result;                  }     /** This method is called from within the constructor to      * initialize the form.      * WARNING: Do NOT modify this code. The content of this method is      * always regenerated by the Form Editor.      */             @SuppressWarnings("unchecked")     // <editor-fold defaultstate="collapsed" desc="Generated Code">     private void initComponents() {          CurrencyBox1 = new javax.swing.JComboBox();         CurrencyBox2 = new javax.swing.JComboBox();         CurrencyText1 = new javax.swing.JTextField();         CurrencyText2 = new javax.swing.JTextField();         ResetButton = new javax.swing.JButton();          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);          CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));         CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 CurrencyBox1ActionPerformed(evt);             }         });          CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD" }));         CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 CurrencyBox2ActionPerformed(evt);             }         });          CurrencyText1.setText("0.0");         CurrencyText1.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 CurrencyText1ActionPerformed(evt);             }         });          CurrencyText2.setText("0.0");         CurrencyText2.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 CurrencyText2ActionPerformed(evt);             }         });          ResetButton.setText("Reset");         ResetButton.addActionListener(new java.awt.event.ActionListener() {             public void actionPerformed(java.awt.event.ActionEvent evt) {                 ResetButtonActionPerformed(evt);             }         });          javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());         getContentPane().setLayout(layout);         layout.setHorizontalGroup(             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGroup(layout.createSequentialGroup()                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                     .addGroup(layout.createSequentialGroup()                         .addContainerGap()                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                             .addComponent(CurrencyText1)                             .addComponent(CurrencyBox1, 0, 125, Short.MAX_VALUE))                         .addGap(126, 126, 126)                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                             .addComponent(CurrencyText2)                             .addComponent(CurrencyBox2, 0, 97, Short.MAX_VALUE)))                     .addGroup(layout.createSequentialGroup()                         .addGap(145, 145, 145)                         .addComponent(ResetButton)))                 .addContainerGap(59, Short.MAX_VALUE))         );         layout.setVerticalGroup(             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGroup(layout.createSequentialGroup()                 .addGap(67, 67, 67)                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                     .addComponent(CurrencyBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                     .addComponent(CurrencyBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                 .addGap(36, 36, 36)                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                     .addComponent(CurrencyText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                     .addComponent(CurrencyText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                 .addGap(63, 63, 63)                 .addComponent(ResetButton)                 .addContainerGap(71, Short.MAX_VALUE))         );          pack();     }// </editor-fold>      private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                                            //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());        //CurrencyConverter currconv = new CurrencyConverter();       //   JComboBox cb = (JComboBox) evt.getSource();         //String from = (String) cb.getSelectedItem();           String from = (String) CurrencyBox2.getSelectedItem();         String to =(String)  CurrencyBox1.getSelectedItem();         //double amount = Double.parseDouble(this.CurrencyText1.getText());           String s=  this.CurrencyText2.getText();                  if(s.trim().length() == 0){  //pop up errort message - input is empty                        return;                            }    double amount = Double.parseDouble(s);         double converted = convert(from, to, amount);              CurrencyText1.setText(df.format(converted) + "");             // double result = cc.convert(from, to, amount); 		//CurrencyBox1.setSelectedItem(new Double(result));       }                                                  private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {                                                      // JComboBox cb = (JComboBox) evt.getSource();        // CurrencyConverter currconv = new CurrencyConverter();         //String from = (String) cb.getSelectedItem();          String from = (String) CurrencyBox1.getSelectedItem();         String to = (String) CurrencyBox2.getSelectedItem();          String s=  CurrencyText1.getText();                if(s.trim().length() == 0){  //pop up errort message - input is empty                         return;                           }             // double amount = Double.parseDouble(this.CurrencyText1.getText());               double amount = Double.parseDouble(s);               System.out.println("from " + from + " to " + to + " amount " + amount);              double converted = convert(from, to, amount);              CurrencyText2.setText(df.format(converted) + "");          //double amount = Double.parseDouble(this.CurrencyText2.getText());               //  double result = cc.convert(from, to, amount); 		//CurrencyBox2.setSelectedItem(new Double(result));     }                                                  private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {                                                       // TODO add your handling code here:     }                                                   private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {                                                       // TODO add your handling code here:     }                                                   private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                     CurrencyText1.setText("");          CurrencyText2.setText("");     }                                                 /**      * @param args the command line arguments      */     public static void main(String args[]) {         /* Set the Nimbus look and feel */         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html           */         try {             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {                 if ("Nimbus".equals(info.getName())) {                     javax.swing.UIManager.setLookAndFeel(info.getClassName());                     break;                 }             }         } catch (ClassNotFoundException ex) {             java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);         } catch (InstantiationException ex) {             java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);         } catch (IllegalAccessException ex) {             java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);         } catch (javax.swing.UnsupportedLookAndFeelException ex) {             java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);         }         //</editor-fold>          /* Create and display the form */         java.awt.EventQueue.invokeLater(new Runnable() {              public void run() {                 try {                     new Converter().setVisible(true);                 } catch (Exception ex) {                     Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);                 }             }         });     }     // Variables declaration - do not modify     private javax.swing.JComboBox CurrencyBox1;     private javax.swing.JComboBox CurrencyBox2;     private javax.swing.JTextField CurrencyText1;     private javax.swing.JTextField CurrencyText2;     private javax.swing.JButton ResetButton;     // End of variables declaration }                             
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 

Select allOpen in new window

asked 12/05/2011 06:47

Abdullah15's gravatar image

Abdullah15 ♦♦


102 Answers:
Something is null at line 166 of Currency.java
link

answered

CEHJ's gravatar image

CEHJ

I couldn't see it on 166. It just do math when I run it which takes numbers from XML file and then do calculate, but when I just chose currency name from selection it gave me this long error. It shows the code bring all the information from XML file and put it down there but  don't give me the convert result on the GUI.
link

answered 2011-12-05 at 14:50:56

Abdullah15's gravatar image

Abdullah15

Try this, and let me know which are the rrors - I dind't have a chance to debug it

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Converter.java
 *
 * Created on Dec 1, 2011, 8:06:24 PM
 */
package Converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;



/**
 *
 * @author Abdullah
 */
public class Converter extends javax.swing.JFrame {

    /** Creates new form Converter */
     String currentPattern;
    private HashMap<String, Double> HashMap1;
    private ArrayList<String> List;
    
    
    

    
    
    
    
    
    
       private ArrayList<String> currencies;;
    private Converter cc;
DecimalFormat df = new DecimalFormat("#####.00");

    /** Creates new form Converter */
    
public Converter() throws Exception{
    initComponents();

HashMap1= new HashMap<String, Double>();
List = new ArrayList<String>();




try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);
String buff = inputLine;

 if(!buff.startsWith("<Cube currency"))continue;
                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );
                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("""));
                  
                  HahsMap1.put(curr, new Double(rate));



}

in.close();
fw.close();
}
catch(Exception e){
System.exit(1);


}
        
//Pattern finalPattern = Pattern.compile("x">([0-9.]+)</span>");
           // Matcher matchFind = finalPattern.matcher();
            //matchFind.find();



        /** Creates new form CurrencyConverterGUI */

     //   initComponents();
        String[] patternExamples = {"USD","JPY","BGN","CZK","DKK","GBP","HUF","LTL","LVL","PLN","RON","SEK","CHF","NOK","HRK","RUB","TRY","AUD',BRL","CAD","CNY","HKD","IDR","ILS","INR","KRW","MXN","MYR","ZD","PHP","SGD","THB","ZAR"};


      // HashMap1 = new HashMap<String, Double>();
        List = new ArrayList<String>();
        currencies = new ArrayList<String>();

      //  populateHashMap();
        
         CurrencyBox1.removeAll();
         CurrencyBox2.removeAll();
         for(String s: currencies){
              CurrencyBox1.addItem(s);  
                CurrencyBox2.addItem(s); 
         }
               CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

              CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        /*
        currentPattern = patternExamples[0];

       for(int j=0; j<patternExamples.length; j++){
        CurrencyBox1.addItem(patternExamples[j]);
          CurrencyBox2.addItem(patternExamples[j]);}
        */
        CurrencyBox1.setEditable(false);
             CurrencyBox2.setEditable(false);

        //CurrencyBox1.addActionListener(this);
    }

    private void populateHashMap() {
        Scanner SC = null;
        try {

            SC = new Scanner(new FileReader(new File("Rates.txt")));
            //SC = new Scanner(new FileReader(new File("Rates.xml")));
        } catch (IOException e) {
            System.err.println("File Error when reading rates.txt file");
            //return;
            System.exit(1);
        }
        
        while (SC.hasNextLine()) {
            String[] S = SC.nextLine().split(" ");
            currencies.add(S[0]);
            HashMap1.put(S[0], Double.valueOf(S[1]));


        

        }
    }
public Object[] getCurrencies() {
		return List.toArray();
	}

	public double convert(String FC, String TC, double amt) {

	double result = amt / HashMap1.get(FC) * HashMap1.get(TC);
		return result;
                 }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
       
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        CurrencyBox1 = new javax.swing.JComboBox();
        CurrencyBox2 = new javax.swing.JComboBox();
        CurrencyText1 = new javax.swing.JTextField();
        CurrencyText2 = new javax.swing.JTextField();
        ResetButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "LTL", "LVL", "PLN", "RON", "SEK", "CHF", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR" }));
        CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

        CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "LTL", "LVL", "PLN", "RON", "SEK", "CHF", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR" }));
        CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        CurrencyText1.setText("0.0");
        CurrencyText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText1ActionPerformed(evt);
            }
        });

        CurrencyText2.setText("0.0");
        CurrencyText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText2ActionPerformed(evt);
            }
        });

        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Times New Roman", 3, 24)); // NOI18N
        jLabel1.setText("Money Converter");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel2.setText("From:");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel3.setText("To:");

        jLabel4.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel4.setText("Result :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(CurrencyText1, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(CurrencyBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, 122, Short.MAX_VALUE))
                            .addComponent(jLabel2))
                        .addGap(86, 86, 86)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(CurrencyText2)
                                .addComponent(CurrencyBox2, 0, 117, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(139, 139, 139)
                        .addComponent(ResetButton)))
                .addContainerGap(83, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(jLabel1)
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addComponent(ResetButton)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyBox1ActionPerformed
       
        //CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD,JPY,BGN,CZK,DKK,GBP,HUF,LTL,LVL,PLN,RON,SEK,CHF,NOK,HRK,RUB,TRY,AUD,BRL,CAD,CNY,HKD,IDR,ILS,INR,KRW,MXN,MYR,ZD,PHP,SGD,THB,ZAR"}));
      //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());
       //CurrencyConverter currconv = new CurrencyConverter();

     //   JComboBox cb = (JComboBox) evt.getSource();
        //String from = (String) cb.getSelectedItem();
          String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyText2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       return;

                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
            // double result = cc.convert(from, to, amount);
		//CurrencyBox1.setSelectedItem(new Double(result));


    }//GEN-LAST:event_CurrencyBox1ActionPerformed

    private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyBox2ActionPerformed
       
       // CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD,JPY,BGN,CZK,DKK,GBP,HUF,LTL,LVL,PLN,RON,SEK,CHF,NOK,HRK,RUB,TRY,AUD,BRL,CAD,CNY,HKD,IDR,ILS,INR,KRW,MXN,MYR,ZD,PHP,SGD,THB,ZAR"}));
        
        
        // JComboBox cb = (JComboBox) evt.getSource();
       // CurrencyConverter currconv = new CurrencyConverter();
        //String from = (String) cb.getSelectedItem();
         String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText1.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted)+ "");

        //double amount = Double.parseDouble(this.CurrencyText2.getText());
              //  double result = cc.convert(from, to, amount);
		//CurrencyBox2.setSelectedItem(new Double(result));
    }//GEN-LAST:event_CurrencyBox2ActionPerformed

    private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyText1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CurrencyText1ActionPerformed

    private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyText2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CurrencyText2ActionPerformed

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetButtonActionPerformed
        CurrencyText1.setText("");

        CurrencyText2.setText("");
    }//GEN-LAST:event_ResetButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Converter().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox CurrencyBox1;
    private javax.swing.JComboBox CurrencyBox2;
    private javax.swing.JTextField CurrencyText1;
    private javax.swing.JTextField CurrencyText2;
    private javax.swing.JButton ResetButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration//GEN-END:variables
}
/*
  String[] temp=null;
        temp= currentfromtext.split(" - ");
        String currFromCode=temp[1];
        
         
          
        temp=convertto.split(" - ");
         String converttoCode=temp[1];
              String URL = "http://finance.yahoo.com/q/bc?s=" + currFromCode + "" + converttoCode + "=X&t=5d&l=on&z=m&q=l&c=";
         try
         {
             String result="";
             URL thePage= new URL(URL);
             BufferedReader in = new BufferedReader(new InputStreamReader(thePage.openStream()));
             
             String InputLine;
             while((InputLine=in.readLine())!=null)
             {
                 result=result+InputLine;
                
             }
             in.close();
 */
link

answered 2011-12-05 at 15:05:55

for_yan's gravatar image

for_yan

corrected after testing the parsing part of the code

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Converter.java
 *
 * Created on Dec 1, 2011, 8:06:24 PM
 */
package Converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;



/**
 *
 * @author Abdullah
 */
public class Converter extends javax.swing.JFrame {

    /** Creates new form Converter */
     String currentPattern;
    private HashMap<String, Double> HashMap1;
    private ArrayList<String> List;
    
    
    

    
    
    
    
    
    
       private ArrayList<String> currencies;;
    private Converter cc;
DecimalFormat df = new DecimalFormat("#####.00");

    /** Creates new form Converter */
    
public Converter() throws Exception{
    initComponents();

HashMap1= new HashMap<String, Double>();
List = new ArrayList<String>();




try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);
String buff = inputLine;

                  if(buff.indexOf("<Cube currency")==-1)continue;
                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );

                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("""));
                 System.out.println(curr + "  " + rate);
                     HashMap1.put(curr, new Double(rate));
                



}

in.close();
fw.close();
}
catch(Exception e){
System.exit(1);


}
        
//Pattern finalPattern = Pattern.compile("x">([0-9.]+)</span>");
           // Matcher matchFind = finalPattern.matcher();
            //matchFind.find();



        /** Creates new form CurrencyConverterGUI */

     //   initComponents();
        String[] patternExamples = {"USD","JPY","BGN","CZK","DKK","GBP","HUF","LTL","LVL","PLN","RON","SEK","CHF","NOK","HRK","RUB","TRY","AUD',BRL","CAD","CNY","HKD","IDR","ILS","INR","KRW","MXN","MYR","ZD","PHP","SGD","THB","ZAR"};


      // HashMap1 = new HashMap<String, Double>();
        List = new ArrayList<String>();
        currencies = new ArrayList<String>();

      //  populateHashMap();
        
         CurrencyBox1.removeAll();
         CurrencyBox2.removeAll();
         for(String s: currencies){
              CurrencyBox1.addItem(s);  
                CurrencyBox2.addItem(s); 
         }
               CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

              CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        /*
        currentPattern = patternExamples[0];

       for(int j=0; j<patternExamples.length; j++){
        CurrencyBox1.addItem(patternExamples[j]);
          CurrencyBox2.addItem(patternExamples[j]);}
        */
        CurrencyBox1.setEditable(false);
             CurrencyBox2.setEditable(false);

        //CurrencyBox1.addActionListener(this);
    }

    private void populateHashMap() {
        Scanner SC = null;
        try {

            SC = new Scanner(new FileReader(new File("Rates.txt")));
            //SC = new Scanner(new FileReader(new File("Rates.xml")));
        } catch (IOException e) {
            System.err.println("File Error when reading rates.txt file");
            //return;
            System.exit(1);
        }
        
        while (SC.hasNextLine()) {
            String[] S = SC.nextLine().split(" ");
            currencies.add(S[0]);
            HashMap1.put(S[0], Double.valueOf(S[1]));


        

        }
    }
public Object[] getCurrencies() {
		return List.toArray();
	}

	public double convert(String FC, String TC, double amt) {

	double result = amt / HashMap1.get(FC) * HashMap1.get(TC);
		return result;
                 }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
       
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        CurrencyBox1 = new javax.swing.JComboBox();
        CurrencyBox2 = new javax.swing.JComboBox();
        CurrencyText1 = new javax.swing.JTextField();
        CurrencyText2 = new javax.swing.JTextField();
        ResetButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "LTL", "LVL", "PLN", "RON", "SEK", "CHF", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR" }));
        CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

        CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "LTL", "LVL", "PLN", "RON", "SEK", "CHF", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR" }));
        CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        CurrencyText1.setText("0.0");
        CurrencyText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText1ActionPerformed(evt);
            }
        });

        CurrencyText2.setText("0.0");
        CurrencyText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText2ActionPerformed(evt);
            }
        });

        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Times New Roman", 3, 24)); // NOI18N
        jLabel1.setText("Money Converter");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel2.setText("From:");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel3.setText("To:");

        jLabel4.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel4.setText("Result :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(CurrencyText1, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(CurrencyBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, 122, Short.MAX_VALUE))
                            .addComponent(jLabel2))
                        .addGap(86, 86, 86)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(CurrencyText2)
                                .addComponent(CurrencyBox2, 0, 117, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(139, 139, 139)
                        .addComponent(ResetButton)))
                .addContainerGap(83, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(jLabel1)
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addComponent(ResetButton)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyBox1ActionPerformed
       
        //CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD,JPY,BGN,CZK,DKK,GBP,HUF,LTL,LVL,PLN,RON,SEK,CHF,NOK,HRK,RUB,TRY,AUD,BRL,CAD,CNY,HKD,IDR,ILS,INR,KRW,MXN,MYR,ZD,PHP,SGD,THB,ZAR"}));
      //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());
       //CurrencyConverter currconv = new CurrencyConverter();

     //   JComboBox cb = (JComboBox) evt.getSource();
        //String from = (String) cb.getSelectedItem();
          String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyText2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       return;

                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
            // double result = cc.convert(from, to, amount);
		//CurrencyBox1.setSelectedItem(new Double(result));


    }//GEN-LAST:event_CurrencyBox1ActionPerformed

    private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyBox2ActionPerformed
       
       // CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD,JPY,BGN,CZK,DKK,GBP,HUF,LTL,LVL,PLN,RON,SEK,CHF,NOK,HRK,RUB,TRY,AUD,BRL,CAD,CNY,HKD,IDR,ILS,INR,KRW,MXN,MYR,ZD,PHP,SGD,THB,ZAR"}));
        
        
        // JComboBox cb = (JComboBox) evt.getSource();
       // CurrencyConverter currconv = new CurrencyConverter();
        //String from = (String) cb.getSelectedItem();
         String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText1.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted)+ "");

        //double amount = Double.parseDouble(this.CurrencyText2.getText());
              //  double result = cc.convert(from, to, amount);
		//CurrencyBox2.setSelectedItem(new Double(result));
    }//GEN-LAST:event_CurrencyBox2ActionPerformed

    private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyText1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CurrencyText1ActionPerformed

    private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyText2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CurrencyText2ActionPerformed

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetButtonActionPerformed
        CurrencyText1.setText("");

        CurrencyText2.setText("");
    }//GEN-LAST:event_ResetButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Converter().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox CurrencyBox1;
    private javax.swing.JComboBox CurrencyBox2;
    private javax.swing.JTextField CurrencyText1;
    private javax.swing.JTextField CurrencyText2;
    private javax.swing.JButton ResetButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration//GEN-END:variables
}
/*
  String[] temp=null;
        temp= currentfromtext.split(" - ");
        String currFromCode=temp[1];
        
         
          
        temp=convertto.split(" - ");
         String converttoCode=temp[1];
              String URL = "http://finance.yahoo.com/q/bc?s=" + currFromCode + "" + converttoCode + "=X&t=5d&l=on&z=m&q=l&c=";
         try
         {
             String result="";
             URL thePage= new URL(URL);
             BufferedReader in = new BufferedReader(new InputStreamReader(thePage.openStream()));
             
             String InputLine;
             while((InputLine=in.readLine())!=null)
             {
                 result=result+InputLine;
                
             }
             in.close();
 */
link

answered 2011-12-05 at 15:41:22

for_yan's gravatar image

for_yan

I am tried to  modify my Currency Converter class to connect to this web site and download the requisite data.  The data source is in XML format, so my application will have to parse the xml data and store it locally in a file.  The HashMap and the ArrayList must then be populated from this local file.

Thanks a lot man but the GUI  disappeared. and give me this result:


link

answered 2011-12-05 at 15:49:07

Abdullah15's gravatar image

Abdullah15

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
run:
<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
	<gesmes:subject>Reference rates</gesmes:subject>
	<gesmes:Sender>
		<gesmes:name>European Central Bank</gesmes:name>
	</gesmes:Sender>
	<Cube>
		<Cube time='2011-12-05'>
			<Cube currency='USD' rate='1.3442'/>
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
link

answered 2011-12-05 at 21:40:27

Abdullah15's gravatar image

Abdullah15

You don't needf to use XML parser to find the rates - look at my code above - it should produce the HashMap of rates which you need
without full XML parsing
link

answered 2011-12-05 at 21:41:07

for_yan's gravatar image

for_yan

I know, I bother you too much about my questions and I know you are a good man. Okay but teacher requested if you think that is enough. I will leave it like this. What about the GUI? it does not show up. Thank you.
link

answered 2011-12-05 at 21:53:53

Abdullah15's gravatar image

Abdullah15


In your original code - did GUI show up?

I didn't try to run your original code - I just added this piece
1:
2:
3:
4:
5:
6:
7:
8:
9:
String buff = inputLine;

                  if(buff.indexOf("<Cube currency")==-1)continue;
                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );

                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("""));
                 System.out.println(curr + "  " + rate);
                     HashMap1.put(curr, new Double(rate));

to populate HashMap1
(and I tested it separately reading from the same file in another program)
and removed two lines below where you populated the HashMap1

After that it shouyld execute the same wayn it was execution before
when you were populationg HashMap1 from the local file

So this chnage should not have affected GUI at all.

If that was exercise on using XML parsers specifically,
then this method of parsing would not work;
if your goal is to make it work - then this methosd
is no worse than any standrad XML parser
as the point is to extract only these specific fields.






link

answered 2011-12-05 at 22:04:34

for_yan's gravatar image

for_yan

Yes it is assignment continue on old one we did. About the GUI it was run. I put picture to see it.

If that was exercise on using XML parsers specifically,
then this method of parsing would not work.    Yes  I tried to  use XML  because it is part of my assignment and I was working on it in class and teacher help us with part. So we add this code to what we have done to make it work with XML. This the code  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);
}

in.close();
fw.close();
}
catch(Exception e){
System.exit(1);


}

  • 13.jpg
    • 383 KB

    GUI is woking before

    GUI is woking before
link

answered 2011-12-05 at 22:11:11

Abdullah15's gravatar image

Abdullah15

  • Rates.xml
    • 1 KB

    after I run old code it create XML file on the computer inside Converter file.Reason in case if there is problem with connection

link

answered 2011-12-05 at 22:25:19

Abdullah15's gravatar image

Abdullah15

>>
if your goal is to make it work - then this methosd
is no worse than any standrad XML parser
as the point is to extract only these specific fields.
>>

At the risk of sounding like John McEnroe - you can't be serious?
link

answered 2011-12-05 at 22:32:57

CEHJ's gravatar image

CEHJ

Okay, but GUI doesn't run. I when I delete the code that for yan gave me, the GUI back to work. I mean appear again.I really need help. Thanks  all of you guys.If you help me to get GUI work too I appreciate that.
link

answered 2011-12-06 at 09:04:47

Abdullah15's gravatar image

Abdullah15

>GUI doesn't run.

Post Stack Trace of the Exception
link

answered 2011-12-06 at 10:23:58

for_yan's gravatar image

for_yan

What I changed has noting to do with the GUI - I just poulated HashMap1 earlier and
therefore removed some codes of generating HashMap1

Perhaps there is some null pointer associated wuith that.

With this NetBeans stuff it is inconvenien for me to run it.

Therefore post StackTrace and we'll locate the problem
link

answered 2011-12-06 at 10:25:06

for_yan's gravatar image

for_yan

Try this - it should run:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Converter.java
 *
 * Created on Dec 1, 2011, 8:06:24 PM
 */
package Converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;



/**
 *
 * @author Abdullah
 */
public class Converter extends javax.swing.JFrame {

    /** Creates new form Converter */
     String currentPattern;
    private HashMap<String, Double> HashMap1;
    private ArrayList<String> List;










       private ArrayList<String> currencies  = new ArrayList<String>();;;
    private Converter cc;
DecimalFormat df = new DecimalFormat("#####.00");

    /** Creates new form Converter */

public Converter() throws Exception{
    initComponents();

HashMap1= new HashMap<String, Double>();
List = new ArrayList<String>();
try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);

String buff = inputLine;

System.out.println(buff);
                  if(buff.indexOf("<Cube currency")==-1)continue;

                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );

                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("'"));
                  System.out.println("buff2: " + buff);
                 System.out.println(curr + "  " + rate);
                     HashMap1.put(curr, new Double(rate));
                     currencies.add(curr);




}

in.close();
fw.close();
}
catch(Exception e){
    e.printStackTrace();
System.exit(1);
}







        /** Creates new form CurrencyConverterGUI */

     //   initComponents();
        String[] patternExamples = {"EUR", "USD"};


       // HashMap1 = new HashMap<String, Double>();
        List = new ArrayList<String>();
        //currencies = new ArrayList<String>();

     //   populateHashMap();

        for(String ss: currencies)System.out.println(ss);
         CurrencyBox1.removeAll();
         CurrencyBox2.removeAll();
         for(String s: currencies){
              CurrencyBox1.addItem(s);
                CurrencyBox2.addItem(s);
         }
               CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

              CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        /*
        currentPattern = patternExamples[0];

       for(int j=0; j<patternExamples.length; j++){
        CurrencyBox1.addItem(patternExamples[j]);
          CurrencyBox2.addItem(patternExamples[j]);}
        */
        CurrencyBox1.setEditable(false);
             CurrencyBox2.setEditable(false);

        //CurrencyBox1.addActionListener(this);
    }

    private void populateHashMap() {
        Scanner SC = null;
        try {

            SC = new Scanner(new FileReader(new File("Rates.txt")));
        } catch (IOException e) {
            System.err.println("File Error when reading rates.txt file");
            //return;
            System.exit(1);
        }
        while (SC.hasNextLine()) {
            String[] S = SC.nextLine().split(" ");
            currencies.add(S[0]);
          //  HashMap1.put(S[0], Double.valueOf(S[1]));




        }
    }
public Object[] getCurrencies() {
		return List.toArray();
	}

	public double convert(String FC, String TC, double amt) {

	double result = amt / HashMap1.get(FC) * HashMap1.get(TC);
		return result;
                 }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        CurrencyBox1 = new javax.swing.JComboBox();
        CurrencyBox2 = new javax.swing.JComboBox();
        CurrencyText1 = new javax.swing.JTextField();
        CurrencyText2 = new javax.swing.JTextField();
        ResetButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));
        CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

        CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD" }));
        CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        CurrencyText1.setText("0.0");
        CurrencyText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText1ActionPerformed(evt);
            }
        });

        CurrencyText2.setText("0.0");
        CurrencyText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText2ActionPerformed(evt);
            }
        });

        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(CurrencyText1)
                            .addComponent(CurrencyBox1, 0, 125, Short.MAX_VALUE))
                        .addGap(126, 126, 126)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(CurrencyText2)
                            .addComponent(CurrencyBox2, 0, 97, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(145, 145, 145)
                        .addComponent(ResetButton)))
                .addContainerGap(59, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(63, 63, 63)
                .addComponent(ResetButton)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {

      //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());
       //CurrencyConverter currconv = new CurrencyConverter();

     //   JComboBox cb = (JComboBox) evt.getSource();
        //String from = (String) cb.getSelectedItem();
          String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyText2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       return;

                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
            // double result = cc.convert(from, to, amount);
		//CurrencyBox1.setSelectedItem(new Double(result));


    }

    private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {
        // JComboBox cb = (JComboBox) evt.getSource();
       // CurrencyConverter currconv = new CurrencyConverter();
        //String from = (String) cb.getSelectedItem();
         String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText1.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");

        //double amount = Double.parseDouble(this.CurrencyText2.getText());
              //  double result = cc.convert(from, to, amount);
		//CurrencyBox2.setSelectedItem(new Double(result));
    }

    private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {
        CurrencyText1.setText("");

        CurrencyText2.setText("");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Converter().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JComboBox CurrencyBox1;
    private javax.swing.JComboBox CurrencyBox2;
    private javax.swing.JTextField CurrencyText1;
    private javax.swing.JTextField CurrencyText2;
    private javax.swing.JButton ResetButton;
    // End of variables declaration
}
link

answered 2011-12-06 at 10:26:49

for_yan's gravatar image

for_yan


Never ever do this things:

1:
2:
3:
4:
5:
6:
}
catch(Exception e){
System.exit(1);


}



If you catch exception - always make a printout withnin the
catch braces, for example like this:

1:
2:
3:
4:
5:
6:
7:
}
catch(Exception e){
e.printStackTrace();
System.exit(1);


}


Otherwise - those are the plces where you can spend most of the time debugging

link

answered 2011-12-06 at 11:03:43

for_yan's gravatar image

for_yan

thanks man. It works now :). I will take your advice about exception. I think always my problems with catch(Exception e). I will pay attention to that in future. I will let you know if I have something in future with is code.I will sit with my teacher to see if there is any thing else  I have to do.  
link

answered 2011-12-06 at 11:06:34

Abdullah15's gravatar image

Abdullah15

Good!
link

answered 2011-12-06 at 11:54:36

for_yan's gravatar image

for_yan

Thanks for yan and any one try to help me.
link

answered 2011-12-06 at 11:56:00

Abdullah15's gravatar image

Abdullah15

This teacher won't accept what we have done :( not easy teacher. He needs  use XMLParser. He gave us example and we can use as much as we can  to make it run  our converter cod run by using XML Parsing.

He  wouldn't recommend submitting the code  that we have done", because he is actually looking for is use of the XML parser as seen when he showed that XMLParser.java file on Products.xml.  I am try to modify XMLParser.java so that it parses currencies instead of products.  So, it will parse the XML from Rates.xml, and look for the cube, currency, rate, and value of the rate.  What I have going on is string parsing, he will take off a lot of points for not using the StAX API for XML. I should keep my GUI that  I built from the last project, and try modifying XMLParser.java from course documents to suit your needs. I put  XML file and XMLParser down. This assignment never finish and hard teacher :(.





The example he gave us :

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package xmlparser;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import javax.xml.namespace.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author subramaniana
 */
public class XMLParser {
    private XMLInputFactory xif;
    private XMLEventReader parser;
    private FileReader infile;

    public void Init(){
        xif = XMLInputFactory.newInstance();
        try{
            infile = new FileReader("products.xml");
            parser = xif.createXMLEventReader(infile);
        }catch(Exception e){
            System.err.println(e);
        }
    }

    public void parseAll(){       
        try{
            while(parser.hasNext()){
                XMLEvent e = parser.nextEvent();
                if(e.isStartElement()){
                    StartElement se = e.asStartElement();
                    String tag = se.getName().getLocalPart();
                    System.out.println("Start Tag Name = " + tag);

                    Iterator<Attribute> it = se.getAttributes();
                    while(it!=null && it.hasNext()){
                        Attribute att = it.next();
                        String AttName = att.getName().toString();
                        String AttVal = att.getValue();
                        System.out.println("Attribute Name = " + AttName);
                        System.out.println("Attribute Value = " + AttVal);
                    }
                }

                if(e.isCharacters()){
                    String TagData=e.asCharacters().getData();
                    System.out.println("Tag Data = " + TagData);
                }

                if(e.isEndElement()){
                    EndElement ee = e.asEndElement();
                    String tag = ee.getName().getLocalPart();
                    System.out.println("End Tag Name = " + tag);
                }           
            }
        }catch(XMLStreamException e){
            System.err.println(e);
        }

        try{
            infile.close();
        }catch(IOException ioe){
            System.err.println(ioe);
        }
    }

    public void parseProduct(String s){
        Init();
        try{
            while(parser.hasNext()){
                XMLEvent e = parser.nextEvent();
                if(e.isStartElement()){
                    StartElement se = e.asStartElement();
                    if(se.getName().getLocalPart().equals("Product")){
                        Attribute IdAtt = se.getAttributeByName(new QName("Id"));
                        if(IdAtt.getValue().equals(s)){
                            System.out.println("Product Id: " + s);
                            while(parser.hasNext()){
                                e=parser.nextEvent();
                                if(e.isStartElement()){
                                    se = e.asStartElement();
                                    String tag = se.getName().getLocalPart();
                                    System.out.println("Start Tag Name = " + tag);

                                    Iterator<Attribute> it = se.getAttributes();
                                    while(it!=null && it.hasNext()){
                                        Attribute att = it.next();
                                        String AttName = att.getName().toString();
                                        String AttVal = att.getValue();
                                        System.out.println("Attribute Name = " + AttName);
                                        System.out.println("Attribute Value = " + AttVal);
                                    }
                                }

                                if(e.isCharacters()){
                                    String TagData=e.asCharacters().getData();
                                    System.out.println("Tag Data = " + TagData);
                                }

                                if(e.isEndElement()){
                                    EndElement ee = e.asEndElement();
                                    String tag = ee.getName().getLocalPart();
                                    if(tag.equals("Product")) return;
                                    System.out.println("End Tag Name = " + tag);
                                }

                            }

                        }
                    }
                }
            }
        }catch(XMLStreamException e){
            System.err.println(e);
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        System.out.println("**************************");
        xp.parseProduct("P2");
    }
}


This XML file does not appear to have any style information associated with it. The document tree is shown below.
     
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
<Inventory>
  <Product Id="P1">
    <Description>Amplifier</Description>
    <Model>AMP1210</Model>
    <Price Currency="USD">1500</Price>
</Product>
<ProductId="P2">
    <Description>Tuner</Description>
    <Model>TR9800</Model>
    <Price Currency="USD">2300</Price>
</Product>
<Product Id="P3">
    <Description>BluRay Player</Description>
    <Model>PS3</Model>
    <Price Currency="USD">500</Price>
    </Product>
</Inventory>
link

answered 2011-12-06 at 11:57:34

Abdullah15's gravatar image

Abdullah15

>>This teacher won't accept what we have done :( not easy teacher. He needs  use XMLParser.

Of course he won't - are you really surprised? I only hope he doesn't find out you got that hacked code from this site
link

answered 2011-12-06 at 13:55:43

CEHJ's gravatar image

CEHJ

>>and hard teacher :(.

And btw, what you have is not a hard teacher, but a GOOD teacher. You're lucky
link

answered 2011-12-06 at 14:36:39

CEHJ's gravatar image

CEHJ

Check this - you should add one more class - XMLParser

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Converter.java
 *
 * Created on Dec 1, 2011, 8:06:24 PM
 */
package Converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;



/**
 *
 * @author Abdullah
 */
public class Converter extends javax.swing.JFrame {

    /** Creates new form Converter */
     String currentPattern;
    private HashMap<String, Double> HashMap1;
    private ArrayList<String> List;










       private ArrayList<String> currencies  = new ArrayList<String>();;;
    private Converter cc;
DecimalFormat df = new DecimalFormat("#####.00");

    /** Creates new form Converter */

public Converter() throws Exception{
    initComponents();

HashMap1= new HashMap<String, Double>();
List = new ArrayList<String>();
try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);

String buff = inputLine;
/*
System.out.println(buff);
                  if(buff.indexOf("<Cube currency")==-1)continue;

                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );

                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("'"));
                  System.out.println("buff2: " + buff);
                 System.out.println(curr + "  " + rate);
                     HashMap1.put(curr, new Double(rate));
                     currencies.add(curr);


                     */




}

in.close();
fw.close();
}
catch(Exception e){
    e.printStackTrace();
System.exit(1);
}







        /** Creates new form CurrencyConverterGUI */

     //   initComponents();
        String[] patternExamples = {"EUR", "USD"};


       // HashMap1 = new HashMap<String, Double>();
        List = new ArrayList<String>();
        //currencies = new ArrayList<String>();

     //   populateHashMap();


        XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        HashMap1 = xp.getHashMap();

        currencies.addAll(HashMap1.keySet());





        for(String ss: currencies)System.out.println(ss);
         CurrencyBox1.removeAll();
         CurrencyBox2.removeAll();
         for(String s: currencies){
              CurrencyBox1.addItem(s);
                CurrencyBox2.addItem(s);
         }
               CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

              CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        /*
        currentPattern = patternExamples[0];

       for(int j=0; j<patternExamples.length; j++){
        CurrencyBox1.addItem(patternExamples[j]);
          CurrencyBox2.addItem(patternExamples[j]);}
        */
        CurrencyBox1.setEditable(false);
             CurrencyBox2.setEditable(false);

        //CurrencyBox1.addActionListener(this);
    }

    private void populateHashMap() {
        Scanner SC = null;
        try {

            SC = new Scanner(new FileReader(new File("Rates.txt")));
        } catch (IOException e) {
            System.err.println("File Error when reading rates.txt file");
            //return;
            System.exit(1);
        }
        while (SC.hasNextLine()) {
            String[] S = SC.nextLine().split(" ");
            currencies.add(S[0]);
          //  HashMap1.put(S[0], Double.valueOf(S[1]));




        }
    }
public Object[] getCurrencies() {
		return List.toArray();
	}

	public double convert(String FC, String TC, double amt) {

	double result = amt / HashMap1.get(FC) * HashMap1.get(TC);
		return result;
                 }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        CurrencyBox1 = new javax.swing.JComboBox();
        CurrencyBox2 = new javax.swing.JComboBox();
        CurrencyText1 = new javax.swing.JTextField();
        CurrencyText2 = new javax.swing.JTextField();
        ResetButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));
        CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

        CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD" }));
        CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        CurrencyText1.setText("0.0");
        CurrencyText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText1ActionPerformed(evt);
            }
        });

        CurrencyText2.setText("0.0");
        CurrencyText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText2ActionPerformed(evt);
            }
        });

        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(CurrencyText1)
                            .addComponent(CurrencyBox1, 0, 125, Short.MAX_VALUE))
                        .addGap(126, 126, 126)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(CurrencyText2)
                            .addComponent(CurrencyBox2, 0, 97, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(145, 145, 145)
                        .addComponent(ResetButton)))
                .addContainerGap(59, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(63, 63, 63)
                .addComponent(ResetButton)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {

      //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());
       //CurrencyConverter currconv = new CurrencyConverter();

     //   JComboBox cb = (JComboBox) evt.getSource();
        //String from = (String) cb.getSelectedItem();
          String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyText2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       return;

                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
            // double result = cc.convert(from, to, amount);
		//CurrencyBox1.setSelectedItem(new Double(result));


    }

    private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {
        // JComboBox cb = (JComboBox) evt.getSource();
       // CurrencyConverter currconv = new CurrencyConverter();
        //String from = (String) cb.getSelectedItem();
         String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText1.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");

        //double amount = Double.parseDouble(this.CurrencyText2.getText());
              //  double result = cc.convert(from, to, amount);
		//CurrencyBox2.setSelectedItem(new Double(result));
    }

    private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {
        CurrencyText1.setText("");

        CurrencyText2.setText("");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Converter().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JComboBox CurrencyBox1;
    private javax.swing.JComboBox CurrencyBox2;
    private javax.swing.JTextField CurrencyText1;
    private javax.swing.JTextField CurrencyText2;
    private javax.swing.JButton ResetButton;
    // End of variables declaration
}



1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Converter;

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//package xmlparser;

import javax.xml.stream.*;
import javax.xml.stream.events.*;
import javax.xml.namespace.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author subramaniana
 */
public class XMLParser {
    private XMLInputFactory xif;
    private XMLEventReader parser;
    private FileReader infile;
    private static HashMap<String, Double> m = new HashMap<String, Double>();
    private String curr;
    private String rat;



    public void Init(){
        xif = XMLInputFactory.newInstance();
        try{
            infile = new FileReader("rates.xml");
            parser = xif.createXMLEventReader(infile);
        }catch(Exception e){
            System.err.println(e);
        }
    }

    public HashMap<String, Double> getHashMap() {
        return m;
    }

    public void parseAll(){
        try{
            while(parser.hasNext()){
                XMLEvent e = parser.nextEvent();
                if(e.isStartElement()){
                    StartElement se = e.asStartElement();
                    String tag = se.getName().getLocalPart();
                    System.out.println("Start Tag Name = " + tag);
                    if(tag.equals("Cube")){
                        curr = null;
                        rat = null;
                    }

                    Iterator<Attribute> it = se.getAttributes();
                    while(it!=null && it.hasNext()){
                        Attribute att = it.next();
                        String AttName = att.getName().toString();
                        String AttVal = att.getValue();
                        System.out.println("Attribute Name = " + AttName);
                        System.out.println("Attribute Value = " + AttVal);
                        if(AttName.equals("rate")) rat = AttVal;
                        else    if(AttName.equals("currency")) curr = AttVal;



                    }
                }

                if(e.isCharacters()){
                    String TagData=e.asCharacters().getData();
                    System.out.println("Tag Data = " + TagData);
                }

                if(e.isEndElement()){
                    EndElement ee = e.asEndElement();
                    String tag = ee.getName().getLocalPart();
                    System.out.println("End Tag Name = " + tag);
                    if(tag.equals("Cube")){

                        if(curr != null && rat != null){
                            m.put(curr, new Double(rat));
                        }
                    }
                }
            }
        }catch(XMLStreamException e){
            System.err.println(e);
        }

        try{
            infile.close();
        }catch(IOException ioe){
            System.err.println(ioe);
        }
    }

    public void parseProduct(String s){
        Init();
        try{
            while(parser.hasNext()){
                XMLEvent e = parser.nextEvent();
                if(e.isStartElement()){
                    StartElement se = e.asStartElement();
                    if(se.getName().getLocalPart().equals("Product")){
                        Attribute IdAtt = se.getAttributeByName(new QName("Id"));
                        if(IdAtt.getValue().equals(s)){
                            System.out.println("Product Id: " + s);
                            while(parser.hasNext()){
                                e=parser.nextEvent();
                                if(e.isStartElement()){
                                    se = e.asStartElement();
                                    String tag = se.getName().getLocalPart();
                                    System.out.println("Start Tag Name = " + tag);

                                    Iterator<Attribute> it = se.getAttributes();
                                    while(it!=null && it.hasNext()){
                                        Attribute att = it.next();
                                        String AttName = att.getName().toString();
                                        String AttVal = att.getValue();
                                        System.out.println("Attribute Name = " + AttName);
                                        System.out.println("Attribute Value = " + AttVal);
                                    }
                                }

                                if(e.isCharacters()){
                                    String TagData=e.asCharacters().getData();
                                    System.out.println("Tag Data = " + TagData);
                                }

                                if(e.isEndElement()){
                                    EndElement ee = e.asEndElement();
                                    String tag = ee.getName().getLocalPart();
                                    if(tag.equals("Product")) return;
                                    System.out.println("End Tag Name = " + tag);
                                }

                            }

                        }
                    }
                }
            }
        }catch(XMLStreamException e){
            System.err.println(e);
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        System.out.println(m);
        System.out.println("**************************");
        xp.parseProduct("P2");
    }
}
link

answered 2011-12-06 at 14:38:23

for_yan's gravatar image

for_yan

No , I just got some help from here and not all code  but part of it,and he will not mind if I got some help. But what he need not exactly  what we have done here as I explained before we are going to use XML Parser.  I thought it is okay  for my teacher if I did differently.  
link

answered 2011-12-06 at 14:42:23

Abdullah15's gravatar image

Abdullah15

But you should of course take XMLParser formthe code I posted above - not your original
link

answered 2011-12-06 at 14:43:33

for_yan's gravatar image

for_yan

>> I thought it is okay  for my teacher if I did differently.  

As long as he doesn't think someone here either gave you or endorsed that code, it's probably not too bad. He will explain to you, if you don't know already (i suspect you have some idea) why the approach in the accepted solution is completely wrong
link

answered 2011-12-06 at 14:45:11

CEHJ's gravatar image

CEHJ

I will try it and I hope he will not struggle me again. I will try it and see if everything is fine. Thanks for yan.
link

answered 2011-12-06 at 14:47:44

Abdullah15's gravatar image

Abdullah15

I reviewed with teacher and see where I am and fix everything before due date.  
link

answered 2011-12-06 at 14:48:28

Abdullah15's gravatar image

Abdullah15


And tell your teacher that your original code was 10 times simpler and required 10 times less time to write and gave exactly the same result and,
if the world would not be full of dogmatic folks who cause us waste so much resources absolutely in vain,
we would all have been already 10 times richer, 10 times healthier, just because we would have been  in the first place 10 times wiser
link

answered 2011-12-06 at 14:50:42

for_yan's gravatar image

for_yan

>>And tell your teacher that your original code was 10 times simpler and required 10 times less time to write

ROFL. Your teacher, if you follow him carefully, will teach you how to write 'dogmatic' (read GOOD) code - which is *exactly* the kind of code you want.
link

answered 2011-12-06 at 14:54:38

CEHJ's gravatar image

CEHJ

it gave me error with
1:
2:
3:
4:
5:
6:
XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        HashMap1 = xp.getHashMap();

        currencies.addAll(HashMap1.keySet());
link

answered 2011-12-06 at 15:02:55

Abdullah15's gravatar image

Abdullah15

Abdullah15, you have accepted an 'answer' to this question now. If you wish to investigate xml methods, please post a new question
link

answered 2011-12-06 at 15:50:43

CEHJ's gravatar image

CEHJ

Do I have to connect first cod to second code.  We can't use old one and add XMl parser and get some code from teacher example.
link

answered 2011-12-06 at 15:55:19

Abdullah15's gravatar image

Abdullah15

Did you use exactly my codes for both programs as posted ID:37246927
or did you cahnge anything?
link

answered 2011-12-06 at 15:55:41

for_yan's gravatar image

for_yan

but I couldn't, I thought  we don of it. I know I became annoy but I need  help. I accepted because I thought it will work for my teacher.
link

answered 2011-12-06 at 15:57:31

Abdullah15's gravatar image

Abdullah15

This code works for me and should work for you the same way.
link

answered 2011-12-06 at 15:58:22

for_yan's gravatar image

for_yan

Why does it print some path to some file called run.xml - there hsould not be such path there.
Did you change anything in any of the two files which I posted ?

I also run them in Netbeans - everything is the same - it shoud work for youa as it works for me
link

answered 2011-12-06 at 15:58:52

for_yan's gravatar image

for_yan

I use first one and I didn't change anything. Should I put them  to gather?. I have not use the second code you put..
link

answered 2011-12-06 at 16:00:21

Abdullah15's gravatar image

Abdullah15

Of course - I wrote you - you need to use both from the same posting
link

answered 2011-12-06 at 16:02:24

for_yan's gravatar image

for_yan

If you want to use a proper xml approach (although not as light as your teacher's), the code for which was NOT supplied by your teacher then you can use something like the below:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import org.xml.sax.InputSource;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.net.MalformedURLException;
import java.net.URL;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

public class RateGetter {

    public static Map<String, Double> getRates(URL url) {
        Map<String, Double> result = new HashMap<String, Double>();
        InputStream in = null;

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder = factory.newDocumentBuilder();

            in = url.openStream();
            Document document = builder.parse(new InputSource(in));
            document.getDocumentElement().normalize();

            XPath xpath = XPathFactory.newInstance().newXPath();

            // Evaluate the document against the pattern
            final String RATES_PATTERN = "//Cube/@currency|//Cube/@rate";
            NodeList nodeList = (NodeList) xpath.evaluate(RATES_PATTERN,
                    document, XPathConstants.NODESET);

            if (nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i += 2) {
		    String currency = nodeList.item(i).getLastChild().getNodeValue();
		    String rate = nodeList.item(i + 1).getLastChild().getNodeValue();
                    result.put(currency, Double.valueOf(rate));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) { /* ignore */
            }
        }

        return result;
    }
}
link

answered 2011-12-06 at 16:05:10

CEHJ's gravatar image

CEHJ

Can you please you give me the "Converte.Java"  that you put two codes and works? I  still have problem with name of the class as First code name the class Converter and package Converter and for second one the code has different  class name. and give error.  
link

answered 2011-12-06 at 16:14:19

Abdullah15's gravatar image

Abdullah15


link

answered 2011-12-06 at 16:29:34

for_yan's gravatar image

for_yan

Theye both should be in the Converter folder because they are both in package Converter
link

answered 2011-12-06 at 16:33:01

for_yan's gravatar image

for_yan

I am really exhausted from This code never come with me correct. Always something wrong. I will let you know man if I still have problem. I don't know what's wrong with
1:
2:
3:
4:
5:
XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        HashMap1 = xp.getHashMap();
link

answered 2011-12-06 at 16:33:38

Abdullah15's gravatar image

Abdullah15

It cannot find file XMLParser - did you put file XMLParser which I sent you into the Converter folder next to Converter.java file?
In folder you should have them side by side and exactly my file
 NetBeansFolder\src\Converter\Converter.java
NetBeansFolder\src\Converter\XMLParser.java


link

answered 2011-12-06 at 17:07:27

for_yan's gravatar image

for_yan

Still problem there :
link

answered 2011-12-06 at 17:16:34

Abdullah15's gravatar image

Abdullah15

link

answered 2011-12-06 at 17:25:51

Abdullah15's gravatar image

Abdullah15

remove this line from Converter.java

import com.sun.org.apache.xerces.internal.parsers.XMLParser;

or maybee better take again my files which I posted ID:37247344
and make sure whatever Netbeans is trying to change in the code - refuse all changes - don't allow it to update - they should work exactly as they come form me

This line was added at the time when you initially put my Converteer
but diidn't put my XMLParser
and beciuse of that line it fails
link

answered 2011-12-06 at 17:31:20

for_yan's gravatar image

for_yan

It was a bad idea to name our own custom file XMLParser becuase this name is used by many packafges.
But you sennt me such file and I didn't cange the name as it worked for me with that name.

Anywasy now is not the time to change - make sure the code is exactly as I posted and it should work
link

answered 2011-12-06 at 17:37:43

for_yan's gravatar image

for_yan

This is how it works for me.

It should work for you !

Make sure that you don't change anything in any of the two java files.
link

answered 2011-12-06 at 17:39:33

for_yan's gravatar image

for_yan

It is works  but  what I did I took the code you posted above and I went to Converter and STC then replace those file and it works but  Old GUI doesn't work and when I compile the cod I got other GUI like what  you have. when I tried to run old GUI design.but until know it is run I still need to work on it. later.Thanks. I hope to see you again later if you don't mind to see if completely satisfied.    
link

answered 2011-12-06 at 17:59:58

Abdullah15's gravatar image

Abdullah15

Sorry, don't understadn anything - does it work or not?
link

answered 2011-12-06 at 18:15:41

for_yan's gravatar image

for_yan

What is STC and what is old GUI?

This is based on your code - as you posted it at the top of this question.
I din't change anything in the GUI part
link

answered 2011-12-06 at 18:17:16

for_yan's gravatar image

for_yan

Yes, it works.  But after I copied both Converter.Java and XMLParser from Above then I replaced them with  mine. Also I got same  picture that you pasted to show me that cod is works. Other thing  I meant by Old design like this picture not any more works. I have to figure out.
 
link

answered 2011-12-06 at 18:20:02

Abdullah15's gravatar image

Abdullah15

OK, thhose are separate points.
It means it is working after all.
Fine.
link

answered 2011-12-06 at 18:28:23

for_yan's gravatar image

for_yan

yes.Thanks I think it's fine. I hope my teacher will not struggle me again.  
link

answered 2011-12-06 at 18:35:01

Abdullah15's gravatar image

Abdullah15

What does mean "Event Handlers don't work - currency conversion doesn't work".  teacher responded when he tried  it. The code work find and convert. Do you think there is something else , I might miss?
link

answered 2011-12-06 at 18:40:22

Abdullah15's gravatar image

Abdullah15

I don't understand what that measn what he responded.
Sure if event handlers don't work it will not work.
But why event handlers would not  work?

Does it work for you?
link

answered 2011-12-12 at 18:29:54

for_yan's gravatar image

for_yan

I have no Idea, I compile it and it works and convert on my computer very good.
Is this mean something or it doesn't matters in this picture
link

answered 2011-12-12 at 19:09:50

Abdullah15's gravatar image

Abdullah15

Change XMLParser.java to the code below and it will not write thta warning
(it by the way was in the code your teacher sent to you - I didn't touvh that part).
Anyway - when you repcae - it will no longer give this woarning.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Converter;

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//package xmlparser;

import javax.xml.stream.*;
import javax.xml.stream.events.*;
import javax.xml.namespace.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author subramaniana
 */
public class XMLParser {
    private XMLInputFactory xif;
    private XMLEventReader parser;
    private FileReader infile;
    private static HashMap<String, Double> m = new HashMap<String, Double>();
    private String curr;
    private String rat;



    public void Init(){
        xif = XMLInputFactory.newInstance();
        try{
            infile = new FileReader("rates.xml");
            parser = xif.createXMLEventReader(infile);
        }catch(Exception e){
            System.err.println(e);
        }
    }

    public HashMap<String, Double> getHashMap() {
        return m;
    }

    public void parseAll(){
        try{
            while(parser.hasNext()){
                XMLEvent e = parser.nextEvent();
                if(e.isStartElement()){
                    StartElement se = e.asStartElement();
                    String tag = se.getName().getLocalPart();
                    System.out.println("Start Tag Name = " + tag);
                    if(tag.equals("Cube")){
                        curr = null;
                        rat = null;
                    }

                    Iterator it = se.getAttributes();
                    while(it!=null && it.hasNext()){
                        Attribute att = (Attribute) it.next();
                        String AttName = att.getName().toString();
                        String AttVal = att.getValue();
                        System.out.println("Attribute Name = " + AttName);
                        System.out.println("Attribute Value = " + AttVal);
                        if(AttName.equals("rate")) rat = AttVal;
                        else    if(AttName.equals("currency")) curr = AttVal;



                    }
                }

                if(e.isCharacters()){
                    String TagData=e.asCharacters().getData();
                    System.out.println("Tag Data = " + TagData);
                }

                if(e.isEndElement()){
                    EndElement ee = e.asEndElement();
                    String tag = ee.getName().getLocalPart();
                    System.out.println("End Tag Name = " + tag);
                    if(tag.equals("Cube")){

                        if(curr != null && rat != null){
                            m.put(curr, new Double(rat));
                        }
                    }
                }
            }
        }catch(XMLStreamException e){
            System.err.println(e);
        }

        try{
            infile.close();
        }catch(IOException ioe){
            System.err.println(ioe);
        }
    }

    public void parseProduct(String s){
        Init();
        try{
            while(parser.hasNext()){
                XMLEvent e = parser.nextEvent();
                if(e.isStartElement()){
                    StartElement se = e.asStartElement();
                    if(se.getName().getLocalPart().equals("Product")){
                        Attribute IdAtt = se.getAttributeByName(new QName("Id"));
                        if(IdAtt.getValue().equals(s)){
                            System.out.println("Product Id: " + s);
                            while(parser.hasNext()){
                                e=parser.nextEvent();
                                if(e.isStartElement()){
                                    se = e.asStartElement();
                                    String tag = se.getName().getLocalPart();
                                    System.out.println("Start Tag Name = " + tag);

                                    Iterator it = se.getAttributes();
                                    while(it!=null && it.hasNext()){
                                        Attribute att = (Attribute)it.next();
                                        String AttName = att.getName().toString();
                                        String AttVal = att.getValue();
                                        System.out.println("Attribute Name = " + AttName);
                                        System.out.println("Attribute Value = " + AttVal);
                                    }
                                }

                                if(e.isCharacters()){
                                    String TagData=e.asCharacters().getData();
                                    System.out.println("Tag Data = " + TagData);
                                }

                                if(e.isEndElement()){
                                    EndElement ee = e.asEndElement();
                                    String tag = ee.getName().getLocalPart();
                                    if(tag.equals("Product")) return;
                                    System.out.println("End Tag Name = " + tag);
                                }

                            }

                        }
                    }
                }
            }
        }catch(XMLStreamException e){
            System.err.println(e);
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        System.out.println(m);
        System.out.println("**************************");
        xp.parseProduct("P2");
    }
}
link

answered 2011-12-12 at 19:35:47

for_yan's gravatar image

for_yan

Okay thanks , I will  use it for my experience and learning .But the  teacher will not change the grade he gave me. I just want know is this warning consider  something wrong with code or fine.
link

answered 2011-12-12 at 19:55:31

Abdullah15's gravatar image

Abdullah15

Do you think this red lines means "Event Handlers don't work - currency conversion doesn't work"?
link

answered 2011-12-12 at 20:05:10

Abdullah15's gravatar image

Abdullah15

>I just want know is this warning consider  something wrong with code or fine

That depedns on the point ov view. In my mind it was better as it was with the warning. What your teacher thinks - I cannot guess.
Besides, this code which generates this warning comes form your teacher. So, I don't think it will affect the grade.


>Do you think this red lines means "Event Handlers don't work - currency conversion doesn't work"?

No I don't think so.
link

answered 2011-12-12 at 20:10:07

for_yan's gravatar image

for_yan

Hard and challenge teacher.  
link

answered 2011-12-12 at 20:13:46

Abdullah15's gravatar image

Abdullah15

Thanks for your respond.
link

answered 2011-12-12 at 20:16:50

Abdullah15's gravatar image

Abdullah15

Ask him what he means by that remark. Write that you execute it and event handlers do work and conversion happens.
link

answered 2011-12-12 at 20:18:06

for_yan's gravatar image

for_yan

I will meet him soon.
link

answered 2011-12-12 at 20:18:08

Abdullah15's gravatar image

Abdullah15

Can you please show me where did change to make that red line disappeared or which code you adjusted?    
link

answered 2011-12-12 at 20:20:16

Abdullah15's gravatar image

Abdullah15

It really does not matter. Better not to give him these ideas. Rather ask him what he meant
link

answered 2011-12-12 at 20:24:54

for_yan's gravatar image

for_yan

I wouldn't  tell him but for my personal, I have to learn  how to avoid  this red line when I want to do something similar  in future.
link

answered 2011-12-12 at 20:37:01

Abdullah15's gravatar image

Abdullah15

For your personal I think there are a lot of much more important things you need to learn much earklier than this stuff

I replaced:
1:
2:
3:
Iterator<Attribute> it = se.getAttributes();
                                    while(it!=null && it.hasNext()){
                                        Attribute att = it.next();


with this:




1:
2:
3:
Iterator it = se.getAttributes();
                                    while(it!=null && it.hasNext()){
                                        Attribute att = (Attribute)it.next();


in two places.

These warinings really do not matter.


link

answered 2011-12-12 at 20:40:35

for_yan's gravatar image

for_yan

Thank you so much man.
link

answered 2011-12-12 at 20:43:46

Abdullah15's gravatar image

Abdullah15

You are always welcome.
link

answered 2011-12-12 at 20:45:55

for_yan's gravatar image

for_yan

I got his answer. He remarked  txtFields and he said  the the project should convert when you write numbers at first txtFeid immediately  and give you the result on the second field not just you write number in the field and then select currency then do convert. He need the listener in all four options. We did only for selections but he haven't put any code in Txtfields.    
link

answered 2011-12-12 at 20:46:19

Abdullah15's gravatar image

Abdullah15

That is easy to do - just add ActionListener to both TextFields and then determine which element  generates event, read the number form that one,
 and read currencies  which are set in the
comboboxes and then do the same calculation as you do know and then populated the other textfiled (the one which did not generate event)
with the result. I'm sure by niow you can do that modification yourself.
link

answered 2011-12-14 at 08:17:42

for_yan's gravatar image

for_yan

This will do with Textbox events.
Mind that ActionEvent in the textbox happens
when user presses RETURN


1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Converter.java
 *
 * Created on Dec 1, 2011, 8:06:24 PM
 */
package Converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;



/**
 *
 * @author Abdullah
 */
public class Converter extends javax.swing.JFrame {

    /** Creates new form Converter */
     String currentPattern;
    private HashMap<String, Double> HashMap1;
    private ArrayList<String> List;










       private ArrayList<String> currencies  = new ArrayList<String>();;;
    private Converter cc;
DecimalFormat df = new DecimalFormat("#####.00");

    /** Creates new form Converter */

public Converter() throws Exception{
    initComponents();

HashMap1= new HashMap<String, Double>();
List = new ArrayList<String>();
try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);

String buff = inputLine;
/*
System.out.println(buff);
                  if(buff.indexOf("<Cube currency")==-1)continue;

                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );

                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("'"));
                  System.out.println("buff2: " + buff);
                 System.out.println(curr + "  " + rate);
                     HashMap1.put(curr, new Double(rate));
                     currencies.add(curr);


                     */




}

in.close();
fw.close();
}
catch(Exception e){
    e.printStackTrace();
System.exit(1);
}







        /** Creates new form CurrencyConverterGUI */

     //   initComponents();
        String[] patternExamples = {"EUR", "USD"};


       // HashMap1 = new HashMap<String, Double>();
        List = new ArrayList<String>();
        //currencies = new ArrayList<String>();

     //   populateHashMap();


        XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        HashMap1 = xp.getHashMap();

        currencies.addAll(HashMap1.keySet());

       




        for(String ss: currencies)System.out.println(ss);
         CurrencyBox1.removeAll();
         CurrencyBox2.removeAll();
         for(String s: currencies){
              CurrencyBox1.addItem(s);
                CurrencyBox2.addItem(s);
         }
               CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

              CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        /*
        currentPattern = patternExamples[0];

       for(int j=0; j<patternExamples.length; j++){
        CurrencyBox1.addItem(patternExamples[j]);
          CurrencyBox2.addItem(patternExamples[j]);}
        */
        CurrencyBox1.setEditable(false);
             CurrencyBox2.setEditable(false);

        //CurrencyBox1.addActionListener(this);
    }

    private void populateHashMap() {
        Scanner SC = null;
        try {

            SC = new Scanner(new FileReader(new File("Rates.txt")));
        } catch (IOException e) {
            System.err.println("File Error when reading rates.txt file");
            //return;
            System.exit(1);
        }
        while (SC.hasNextLine()) {
            String[] S = SC.nextLine().split(" ");
            currencies.add(S[0]);
          //  HashMap1.put(S[0], Double.valueOf(S[1]));




        }
    }
public Object[] getCurrencies() {
		return List.toArray();
	}

	public double convert(String FC, String TC, double amt) {
          //  System.out.println("HashMap1: " + HashMap1);
          //  System.out.println("FC: " + FC);
          //     System.out.println("TC: " + TC);

	double result = amt / HashMap1.get(FC) * HashMap1.get(TC);
		return result;
                 }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        CurrencyBox1 = new javax.swing.JComboBox();
        CurrencyBox2 = new javax.swing.JComboBox();
        CurrencyText1 = new javax.swing.JTextField();
        CurrencyText2 = new javax.swing.JTextField();
        ResetButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD"}));
        CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

        CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"USD" }));
        CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        CurrencyText1.setText("0.0");
        CurrencyText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText1ActionPerformed(evt);
            }
        });

        CurrencyText2.setText("0.0");
        CurrencyText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText2ActionPerformed(evt);
            }
        });

        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(CurrencyText1)
                            .addComponent(CurrencyBox1, 0, 125, Short.MAX_VALUE))
                        .addGap(126, 126, 126)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(CurrencyText2)
                            .addComponent(CurrencyBox2, 0, 97, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(145, 145, 145)
                        .addComponent(ResetButton)))
                .addContainerGap(59, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CurrencyText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CurrencyText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(63, 63, 63)
                .addComponent(ResetButton)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {

      //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());
       //CurrencyConverter currconv = new CurrencyConverter();

     //   JComboBox cb = (JComboBox) evt.getSource();
        //String from = (String) cb.getSelectedItem();
          String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyText2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       return;

                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
            // double result = cc.convert(from, to, amount);
		//CurrencyBox1.setSelectedItem(new Double(result));


    }

    private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {
        // JComboBox cb = (JComboBox) evt.getSource();
       // CurrencyConverter currconv = new CurrencyConverter();
        //String from = (String) cb.getSelectedItem();
         String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText1.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");

        //double amount = Double.parseDouble(this.CurrencyText2.getText());
              //  double result = cc.convert(from, to, amount);
		//CurrencyBox2.setSelectedItem(new Double(result));
    }

    private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
               String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText1.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");



    }

    private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
               String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText2.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");

    }

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {
        CurrencyText1.setText("");

        CurrencyText2.setText("");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Converter().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JComboBox CurrencyBox1;
    private javax.swing.JComboBox CurrencyBox2;
    private javax.swing.JTextField CurrencyText1;
    private javax.swing.JTextField CurrencyText2;
    private javax.swing.JButton ResetButton;
    // End of variables declaration
}
link

answered 2011-12-14 at 09:18:16

for_yan's gravatar image

for_yan


Thanks.I did as you did , but it same, it doesn't'  change any thing like when I write number in Txtfield do nothing. I mean nothing change in the second txtField.
link

answered 2011-12-14 at 10:35:21

Abdullah15's gravatar image

Abdullah15

I did add this part  to Txtfield but it doesn't work why?I seems not easy to do.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
// TODO add your handling code here:
               String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText2.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");
link

answered 2011-12-14 at 11:10:26

Abdullah15's gravatar image

Abdullah15

Take my code from 37287106 and it should wiork

It works from me - it should work for you.

Make sure that you make RETURN after typing the last chracter in the textfiled - it would not work otherwise - it acnnot know if you ended input

With RETURN -it must work -but use the whole my code instaed ofg your Converter.java

link

answered 2011-12-14 at 13:16:10

for_yan's gravatar image

for_yan

Can you please look to this code and run it. I might explained what I need in wrong way. This code will show you exactly. Please check it.
link

answered 2011-12-14 at 13:20:25

Abdullah15's gravatar image

Abdullah15

I did put Return but Still doesn't work . This what I have.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
package Converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;

/**
 *
 * @author Abdullah
 */
public class Converter1 extends javax.swing.JFrame {
/** Creates new form Converter */
     String currentPattern;
    private HashMap<String, Double> HashMap1;
    private ArrayList<String> List;










       private ArrayList<String> currencies  = new ArrayList<String>();;;
    private Converter1 cc;
DecimalFormat df = new DecimalFormat("#####.00");

    /** Creates new form Converter */

public Converter1() throws Exception{
    initComponents();

HashMap1= new HashMap<String, Double>();
List = new ArrayList<String>();
try{
 URL ecb = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(ecb.openStream()));
FileWriter fw = new FileWriter("Rates.xml");
String inputLine;


while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
fw.write(inputLine);

String buff = inputLine;
/*
System.out.println(buff);
                  if(buff.indexOf("<Cube currency")==-1)continue;

                String curr = buff.substring(buff.indexOf("ency=") + 6, buff.indexOf("ency=") +9 );

                  String rate = buff.substring(buff.indexOf("ate=") + 5, buff.lastIndexOf("'"));
                  System.out.println("buff2: " + buff);
                 System.out.println(curr + "  " + rate);
                     HashMap1.put(curr, new Double(rate));
                     currencies.add(curr);


                     */




}

in.close();
fw.close();
}
catch(Exception e){
    e.printStackTrace();
System.exit(1);
}







        /** Creates new form CurrencyConverterGUI */

     //   initComponents();
        String[] patternExamples = {"EUR", "USD"};


       // HashMap1 = new HashMap<String, Double>();
        List = new ArrayList<String>();
        //currencies = new ArrayList<String>();

     //   populateHashMap();


        XMLParser xp = new XMLParser();
        xp.Init();
        xp.parseAll();
        HashMap1 = xp.getHashMap();

        currencies.addAll(HashMap1.keySet());

       




        for(String ss: currencies)System.out.println(ss);
         CurrencyBox1.removeAll();
         CurrencyBox2.removeAll();
         for(String s: currencies){
              CurrencyBox1.addItem(s);
                CurrencyBox2.addItem(s);
         }
               CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });

              CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });

        /*
        currentPattern = patternExamples[0];

       for(int j=0; j<patternExamples.length; j++){
        CurrencyBox1.addItem(patternExamples[j]);
          CurrencyBox2.addItem(patternExamples[j]);}
        */
        CurrencyBox1.setEditable(false);
             CurrencyBox2.setEditable(false);

        //CurrencyBox1.addActionListener(this);
    }

    private void populateHashMap() {
        Scanner SC = null;
        try {

            SC = new Scanner(new FileReader(new File("Rates.txt")));
        } catch (IOException e) {
            System.err.println("File Error when reading rates.txt file");
            //return;
            System.exit(1);
        }
        while (SC.hasNextLine()) {
            String[] S = SC.nextLine().split(" ");
            currencies.add(S[0]);
          //  HashMap1.put(S[0], Double.valueOf(S[1]));




        }
    }
public Object[] getCurrencies() {
		return List.toArray();
	}

	public double convert(String FC, String TC, double amt) {
          //  System.out.println("HashMap1: " + HashMap1);
          //  System.out.println("FC: " + FC);
          //     System.out.println("TC: " + TC);

	double result = amt / HashMap1.get(FC) * HashMap1.get(TC);
		return result;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ResetButton = new javax.swing.JButton();
        CurrencyBox1 = new javax.swing.JComboBox();
        CurrencyBox2 = new javax.swing.JComboBox();
        CurrencyText1 = new javax.swing.JTextField();
        CurrencyText2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        ResetButton.setFont(new java.awt.Font("Times New Roman", 3, 14));
        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });
        getContentPane().add(ResetButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 250, -1, -1));

        CurrencyBox1.setFont(new java.awt.Font("Times New Roman", 3, 14));
        CurrencyBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "LTL", "LVL", "PLN", "RON", "SEK", "CHF", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR" }));
        CurrencyBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox1ActionPerformed(evt);
            }
        });
        getContentPane().add(CurrencyBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 91, 120, -1));

        CurrencyBox2.setFont(new java.awt.Font("Times New Roman", 3, 14));
        CurrencyBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "LTL", "LVL", "PLN", "RON", "SEK", "CHF", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR" }));
        CurrencyBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyBox2ActionPerformed(evt);
            }
        });
        getContentPane().add(CurrencyBox2, new org.netbeans.lib.awtextra.AbsoluteConstraints(199, 91, 120, -1));

        CurrencyText1.setText("0.0");
        CurrencyText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText1ActionPerformed(evt);
            }
        });
        getContentPane().add(CurrencyText1, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 186, 120, -1));

        CurrencyText2.setText("0.0");
        CurrencyText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CurrencyText2ActionPerformed(evt);
            }
        });
        getContentPane().add(CurrencyText2, new org.netbeans.lib.awtextra.AbsoluteConstraints(199, 186, 120, -1));

        jLabel1.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel1.setText("From:");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 68, -1, -1));

        jLabel2.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel2.setText("To");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(199, 68, -1, -1));

        jLabel3.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N
        jLabel3.setText("The Result:");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 163, -1, -1));

        jLabel4.setFont(new java.awt.Font("Times New Roman", 3, 24)); // NOI18N
        jLabel4.setText(" Converter");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 20, -1, -1));

        jLabel5.setFont(new java.awt.Font("PMingLiU", 3, 18)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 255, 0));
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        pack();
    }// </editor-fold>                        

    private void CurrencyBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                             
      //  CurrencyText1 = new JFormattedTextField(NumberFormat.getInstance());
       //CurrencyConverter currconv = new CurrencyConverter();

     //   JComboBox cb = (JComboBox) evt.getSource();
        //String from = (String) cb.getSelectedItem();
          String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyText2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       return;

                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
            // double result = cc.convert(from, to, amount);
		//CurrencyBox1.setSelectedItem(new Double(result));

    }                                            

    private void CurrencyBox2ActionPerformed(java.awt.event.ActionEvent evt) {                                             
         // TODO add your handling code here:
               String from = (String) CurrencyBox1.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText2.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText1.setText(df.format(converted) + "");
    }                                            

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        CurrencyText1.setText("");

        CurrencyText2.setText("");
    }                                           

    private void CurrencyText1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
               String from = (String) CurrencyBox2.getSelectedItem();
        String to = (String) CurrencyBox1.getSelectedItem();
         String s=  CurrencyText2.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");

    }                                             

    private void CurrencyText2ActionPerformed(java.awt.event.ActionEvent evt) {                                              
       // TODO add your handling code here:
               String from = (String) CurrencyBox2.getSelectedItem();
        String to = (String) CurrencyBox2.getSelectedItem();
         String s=  CurrencyText2.getText();
               if(s.trim().length() == 0){

//pop up errort message - input is empty
                        return;

                         }

           // double amount = Double.parseDouble(this.CurrencyText1.getText());

             double amount = Double.parseDouble(s);

             System.out.println("from " + from + " to " + to + " amount " + amount);

            double converted = convert(from, to, amount);

            CurrencyText2.setText(df.format(converted) + "");

    }                                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Converter1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Converter1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Converter1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Converter1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Converter1().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(Converter1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JComboBox CurrencyBox1;
    private javax.swing.JComboBox CurrencyBox2;
    private javax.swing.JTextField CurrencyText1;
    private javax.swing.JTextField CurrencyText2;
    private javax.swing.JButton ResetButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration                   
}
link

answered 2011-12-14 at 13:33:48

Abdullah15's gravatar image

Abdullah15



No this is not exactly the same code which I posted.
Use exactly my code - it works for me, it should work for you.

link

answered 2011-12-14 at 13:37:37

for_yan's gravatar image

for_yan

Can you send me the file. Because I think for me no way to get it work. I coped exactly.
link

answered 2011-12-14 at 13:43:50

Abdullah15's gravatar image

Abdullah15

Tried again - it works for me.
Replace your file with this one.
It should work.
link

answered 2011-12-14 at 14:19:27

for_yan's gravatar image

for_yan

Okay, Thanks . I give up. So tired of Java. If I have to work with java and each time problem like this.I might end up sick. I can't try any more.
link

answered 2011-12-14 at 14:25:47

Abdullah15's gravatar image

Abdullah15

I think you should just study it from earlier stage.
I think this program and this activity is too complex for your stage of mastering java environment.
You should start with more simple programs and first be more compfortable
with all things about IDE, packages, and this kind of stuff.
And more stepwise learning should not be so painful.

link

answered 2011-12-14 at 14:43:55

for_yan's gravatar image

for_yan

I really like Java and programing and I am trying as much as I can. I will try until I become familiar with everything.I think to be good at it not easy and not coming even in three months of practicing. I am trying to understand every single thing in the cod and what does it mean. I like this webside when I have hard time for sure I can see who will help me here. I appreciate your help.
link

answered 2011-12-14 at 15:08:08

Abdullah15's gravatar image

Abdullah15

I just want to ask you. Is there something you changer other then put this code inside TxtField?
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
String from = (String) CurrencyBox2.getSelectedItem();
        String to =(String)  CurrencyBox1.getSelectedItem();
        //double amount = Double.parseDouble(this.CurrencyText1.getText());
          String s=  this.CurrencyTxt2.getText();
                 if(s.trim().length() == 0){

//pop up errort message - input is empty
                       
 return;
                          }

  double amount = Double.parseDouble(s);

       double converted = convert(from, to, amount);

            CurrencyTxt1.setText(df.format(converted) + "");
link

answered 2011-12-14 at 15:22:42

Abdullah15's gravatar image

Abdullah15

Yes, I did.
link

answered 2011-12-14 at 16:15:52

for_yan's gravatar image

for_yan

Take my code and execute.

It should work.


link

answered 2011-12-14 at 16:24:01

for_yan's gravatar image

for_yan

Where ?Please
link

answered 2011-12-14 at 16:25:04

Abdullah15's gravatar image

Abdullah15

No, I would not tell you until you confirm that it executes.
Otherwise we are wasting time.
I was thinking that you took my code and was executing it.
And if you are not doing it, then waht is the point?
link

answered 2011-12-14 at 16:25:32

for_yan's gravatar image

for_yan

Okay even I didn't change your code at all but I will do my best to figure even if I spend all my day to figure it. Thanks
link

answered 2011-12-14 at 16:27:47

Abdullah15's gravatar image

Abdullah15

But does it work for you as it is without any changes?
link

answered 2011-12-14 at 16:43:42

for_yan's gravatar image

for_yan

No, but I will try. Until I get it.
link

answered 2011-12-14 at 16:44:57

Abdullah15's gravatar image

Abdullah15

In waht sense it does not work ?
Does it report any error?
link

answered 2011-12-14 at 16:58:40

for_yan's gravatar image

for_yan

Sorry, I meant the part in txtField didn't work on my code or on my computer. Thanks for your help.
link

answered 2011-12-14 at 16:59:37

Abdullah15's gravatar image

Abdullah15

Sorry, please be clear.
This is not understandble:
>part in txtField didn't work on my code or on my computer


I'm asking - did you take my file,  posted ID:37288353, did you put it in your project folder
replacing yours - and then ran it and after you enetered number in textfield and then Enter
the number in another textbox didn't change?
Please, reply clearly without ambiguities, what you did, with what code, and what you observed

If it did not work, did you see any exception?

link

answered 2011-12-14 at 22:00:47

for_yan's gravatar image

for_yan

I meant I tried and I didn't get  txtfiiel yet work, I am sue I have problem.There is no error or exception and it is run perfect except the txtfield part.I coped yours and I might missing something. I will let you know when I fiend what I am missing. I tried to be more clear as much as I can.I need just more time.I will come back to you and tell you if I still have  same question.
link

answered 2011-12-14 at 22:07:50

Abdullah15's gravatar image

Abdullah15

>I coped yours and I might missing something

I can't undersatn what you mean.
Take the file I attached and put it therein the src/Converter foldr and copy your previous file to some other place
How can you "miss something" - that is not understandable.
link

answered 2011-12-14 at 23:19:49

for_yan's gravatar image

for_yan

Okay, I will
link

answered 2011-12-14 at 23:22:26

Abdullah15's gravatar image

Abdullah15

Your answer
[hide preview]

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Tags:

Asked: 12/05/2011 06:47

Seen: 301 times

Last updated: 12/06/2011 03:57