Abdullah Abdulkarim
asked on
I need help with Currency Converter code reading from XML file.
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.
6.jpg
10.jpg
11.jpg
/*
* 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
}
7.jpg6.jpg
10.jpg
11.jpg
Something is null at line 166 of Currency.java
ASKER
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.
Converter.java
Converter.java
Try this, and let me know which are the rrors - I dind't have a chance to debug it
/*
* 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();
*/
corrected after testing the parsing part of the code
/*
* 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();
*/
ASKER
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:
12.jpg
Thanks a lot man but the GUI disappeared. and give me this result:
12.jpg
ASKER
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)
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
without full XML parsing
ASKER
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.
In your original code - did GUI show up?
I didn't try to run your original code - I just added this piece
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.
ASKER
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
13.jpg
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
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
ASKER
>>
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?
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?
ASKER
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.
>GUI doesn't run.
Post Stack Trace of the Exception
Post Stack Trace of the Exception
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Never ever do this things:
}
catch(Exception e){
System.exit(1);
}
If you catch exception - always make a printout withnin the
catch braces, for example like this:
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
Otherwise - those are the plces where you can spend most of the time debugging
ASKER
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.
Good!
ASKER
Thanks for yan and any one try to help me.
ASKER
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 :
This XML file does not appear to have any style information associated with it. The document tree is shown below.
Products.XML
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 :
/*
* 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.
<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>
XMLParser.javaProducts.XML
>>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
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
>>and hard teacher :(.
And btw, what you have is not a hard teacher, but a GOOD teacher. You're lucky
And btw, what you have is not a hard teacher, but a GOOD teacher. You're lucky
Check this - you should add one more class - XMLParser
/*
* 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
}
/*
* 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");
}
}
ASKER
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.
But you should of course take XMLParser formthe code I posted above - not your original
>> 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
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
ASKER
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.
ASKER
I reviewed with teacher and see where I am and fix everything before due date.
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
>>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.
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.
ASKER
it gave me error with
XMLParser xp = new XMLParser();
xp.Init();
xp.parseAll();
HashMap1 = xp.getHashMap();
currencies.addAll(HashMap1.keySet());
15.jpg
Abdullah15, you have accepted an 'answer' to this question now. If you wish to investigate xml methods, please post a new question
ASKER
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.
Did you use exactly my codes for both programs as posted ID:37246927
or did you cahnge anything?
or did you cahnge anything?
ASKER
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.
This code works for me and should work for you the same way.
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
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
ASKER
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..
Of course - I wrote you - you need to use both from the same posting
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:
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;
}
}
ASKER
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.
Theye both should be in the Converter folder because they are both in package Converter
ASKER
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
XMLParser xp = new XMLParser();
xp.Init();
xp.parseAll();
HashMap1 = xp.getHashMap();
16.jpg
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\Convert er\Convert er.java
NetBeansFolder\src\Convert er\XMLPars er.java
In folder you should have them side by side and exactly my file
NetBeansFolder\src\Convert
NetBeansFolder\src\Convert
ASKER
ASKER
remove this line from Converter.java
import com.sun.org.apache.xerces. internal.p arsers.XML Parser;
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
import com.sun.org.apache.xerces.
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
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
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
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.
converter.PNG
It should work for you !
Make sure that you don't change anything in any of the two java files.
converter.PNG
ASKER
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.
Sorry, don't understadn anything - does it work or not?
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
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
ASKER
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.
19.jpg
19.jpg
OK, thhose are separate points.
It means it is working after all.
Fine.
It means it is working after all.
Fine.
ASKER
yes.Thanks I think it's fine. I hope my teacher will not struggle me again.
ASKER
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?
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?
Sure if event handlers don't work it will not work.
But why event handlers would not work?
Does it work for you?
ASKER
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
29.jpg
Is this mean something or it doesn't matters in this picture
29.jpg
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.
(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.
/*
* 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");
}
}
ASKER
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.
ASKER
Do you think this red lines means "Event Handlers don't work - currency conversion doesn't work"?
>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.
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.
ASKER
Hard and challenge teacher.
ASKER
Thanks for your respond.
Ask him what he means by that remark. Write that you execute it and event handlers do work and conversion happens.
ASKER
I will meet him soon.
ASKER
Can you please show me where did change to make that red line disappeared or which code you adjusted?
It really does not matter. Better not to give him these ideas. Rather ask him what he meant
ASKER
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.
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:
with this:
in two places.
These warinings really do not matter.
I replaced:
Iterator<Attribute> it = se.getAttributes();
while(it!=null && it.hasNext()){
Attribute att = it.next();
with this:
Iterator it = se.getAttributes();
while(it!=null && it.hasNext()){
Attribute att = (Attribute)it.next();
in two places.
These warinings really do not matter.
ASKER
Thank you so much man.
You are always welcome.
ASKER
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.
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.
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.
This will do with Textbox events.
Mind that ActionEvent in the textbox happens
when user presses RETURN
Mind that ActionEvent in the textbox happens
when user presses RETURN
/*
* 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
}
ASKER
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.
ASKER
I did add this part to Txtfield but it doesn't work why?I seems not easy to do.
// 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) + "");
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
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
ASKER
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.
CurrencyConverterGUI.java
CurrencyConverterGUI.java
ASKER
I did put Return but Still doesn't work . This what I have.
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
}
No this is not exactly the same code which I posted.
Use exactly my code - it works for me, it should work for you.
ASKER
Can you send me the file. Because I think for me no way to get it work. I coped exactly.
ASKER
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.
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.
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.
ASKER
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.
ASKER
I just want to ask you. Is there something you changer other then put this code inside TxtField?
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) + "");
Yes, I did.
Take my code and execute.
It should work.
It should work.
ASKER
Where ?Please
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?
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?
ASKER
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
But does it work for you as it is without any changes?
ASKER
No, but I will try. Until I get it.
In waht sense it does not work ?
Does it report any error?
Does it report any error?
ASKER
Sorry, I meant the part in txtField didn't work on my code or on my computer. Thanks for your help.
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?
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?
ASKER
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.
>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.
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.
ASKER
Okay, I will