Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package currencyconverter;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.ObjectInput;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutput;
- import java.io.ObjectOutputStream;
- import java.io.OutputStream;
- import java.io.Serializable;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.text.DecimalFormat;
- import java.util.ArrayList;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.JOptionPane;
- import javax.xml.stream.XMLInputFactory;
- import javax.xml.stream.XMLStreamConstants;
- import javax.xml.stream.XMLStreamException;
- import javax.xml.stream.XMLStreamReader;
- /**
- *
- * @author Sandkar
- */
- /*
- HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!HUOM!
- To get the correct JavaDoc you have to go to:
- Run -> Set Project Configuration -> Customize -> Documenting -> check Include Private and Package Private Members
- */
- /**
- * Main window for the currency converter
- */
- public class CurrencyConverter extends javax.swing.JFrame implements Serializable {
- private ArrayList<Currency> currencies = new ArrayList<>();
- private String time = new String();
- private Double currentFromRate;
- private Double currentToRate;
- private final DecimalFormat df;
- /**
- * Creates new form CurrencyConverter
- */
- public CurrencyConverter() throws IOException {
- this.openCurrencyXML();
- this.df = new DecimalFormat("#.#####");
- this.currentFromRate = new Double(1);
- this.currentToRate = new Double(1);
- initComponents();
- for(int i = 1; i < currencies.size(); ++i) {
- jComboBox1.addItem(currencies.get(i).getName());
- jComboBox2.addItem(currencies.get(i).getName());
- }
- jLabel1.setText("Rates from: " + currencies.get(0).getDate());
- }
- @SuppressWarnings("unchecked")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">
- private void initComponents() {
- jComboBox1 = new javax.swing.JComboBox();
- jLabel1 = new javax.swing.JLabel();
- jComboBox2 = new javax.swing.JComboBox();
- jLabel2 = new javax.swing.JLabel();
- jLabel3 = new javax.swing.JLabel();
- jLabel4 = new javax.swing.JLabel();
- jLabel5 = new javax.swing.JLabel();
- jTextField1 = new javax.swing.JTextField();
- jTextField2 = new javax.swing.JTextField();
- setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
- setTitle("Ye Olde Currency Converter - Avast Ye Swashbucklers");
- jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));
- jComboBox1.setToolTipText("");
- jComboBox1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jComboBox1ActionPerformed(evt);
- }
- });
- jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EUR" }));
- jComboBox2.setToolTipText("");
- jComboBox2.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jComboBox2ActionPerformed(evt);
- }
- });
- jLabel2.setText("From");
- jLabel3.setText("To");
- jLabel4.setText("Amount");
- jLabel5.setText("Result");
- jTextField1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jTextField1ActionPerformed(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()
- .addContainerGap()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(jLabel4)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGroup(layout.createSequentialGroup()
- .addComponent(jLabel5)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGroup(layout.createSequentialGroup()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jLabel2)
- .addComponent(jLabel3))
- .addGap(25, 25, 25)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)))
- .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGap(18, 18, Short.MAX_VALUE))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addContainerGap()
- .addComponent(jLabel1)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(jLabel2))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(jLabel3))
- .addGap(18, 18, 18)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jLabel4)
- .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGap(18, 18, 18)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jLabel5)
- .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addContainerGap(22, Short.MAX_VALUE))
- );
- pack();
- }// </editor-fold>
- /**
- * Outputs the correct amount depending on which rate you have chosen
- */
- private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- jTextField2.setText(df.format(Double.parseDouble(jTextField1.getText()) * currentToRate / currentFromRate));
- }
- /**
- * Updates your current from rate
- */
- private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- currentFromRate = currencies.get(jComboBox1.getSelectedIndex()).getRate();
- }
- /**
- * Updates your current to rate
- */
- private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- currentToRate = currencies.get(jComboBox2.getSelectedIndex()).getRate();
- }
- /**
- * Reads the currencies name, rate and date into a list
- */
- private void writeToFile() throws IOException {
- File file = new File(System.getProperty("user.home") + "/currencies.cur");
- if(!file.exists()) {
- file.createNewFile();
- }
- try(OutputStream out = new FileOutputStream(file.getPath());
- OutputStream buffer = new BufferedOutputStream(out);
- ObjectOutput output = new ObjectOutputStream(buffer);) {
- output.writeObject(currencies);
- } catch (IOException e) {
- }
- }
- /**
- * Reads the currencies name, rate and date into a list
- */
- private void readFromFile() throws IOException {
- File file = new File(System.getProperty("user.home") + "/currencies.cur");
- try(InputStream in = new FileInputStream(file.getPath());
- InputStream buffer = new BufferedInputStream(in);
- ObjectInput input = new ObjectInputStream(buffer);) {
- currencies = (ArrayList<Currency>) input.readObject();
- } catch (FileNotFoundException ex) {
- showErrorMsg("Could not fetch rates online and no cached file found.");
- System.exit(0);
- } catch (IOException | ClassNotFoundException ex) {
- showErrorMsg("Could not fetch rates online and no cached file found.");
- System.exit(0);
- }
- }
- /**
- * Shows the parameter as an information message
- */
- private static void showInformationMsg(String msg) {
- JOptionPane.showMessageDialog(
- null,
- msg,
- "Information",
- JOptionPane.INFORMATION_MESSAGE);
- }
- /**
- * Shows the parameter as an error message
- */
- private static void showErrorMsg(String msg) {
- JOptionPane.showMessageDialog(
- null,
- msg,
- "Error",
- JOptionPane.ERROR_MESSAGE);
- }
- /**
- * Reads the XML currency file into a list, if no connection is found it reads from a .cur file in the home folder. If no .cur file is found it terminates the program.
- */
- private void openCurrencyXML() throws IOException {
- XMLInputFactory factory = XMLInputFactory.newInstance();
- URL url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
- try {
- InputStream stream = url.openStream();
- XMLStreamReader reader = factory.createXMLStreamReader(stream);
- while(reader.hasNext()) {
- int event = reader.next();
- switch (event) {
- case XMLStreamConstants.START_ELEMENT:
- String attributeValue = reader.getAttributeValue(0);
- String attributeValue2 = reader.getAttributeValue(1);
- String attributeName = reader.getAttributeLocalName(0);
- if("time".equals(attributeName)) {
- time = attributeValue;
- currencies.add(new Currency("EUR", (double) 1, time)); // Puts the "base" in there as well
- }
- if("currency".equals(attributeName))
- currencies.add(new Currency(attributeValue, Double.parseDouble(attributeValue2), time));
- break;
- case XMLStreamConstants.CHARACTERS:
- if (!reader.isWhiteSpace()) {
- String contents = reader.getText().trim();
- }
- break;
- }
- }
- this.writeToFile();
- }
- catch(IOException | XMLStreamException | NumberFormatException e) {
- readFromFile();
- showInformationMsg("Could not fetch rates online, using cached file instead.");
- }
- }
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) throws MalformedURLException, IOException, XMLStreamException {
- /* 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(CurrencyConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- }
- //</editor-fold>
- //</editor-fold>
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(() -> {
- try {
- new CurrencyConverter().setVisible(true);
- } catch (IOException ex) {
- Logger.getLogger(CurrencyConverter.class.getName()).log(Level.SEVERE, null, ex);
- }
- });
- }
- // Variables declaration - do not modify
- private static javax.swing.JComboBox jComboBox1;
- private static javax.swing.JComboBox jComboBox2;
- private static javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JLabel jLabel3;
- private javax.swing.JLabel jLabel4;
- private javax.swing.JLabel jLabel5;
- private javax.swing.JTextField jTextField1;
- private javax.swing.JTextField jTextField2;
- // End of variables declaration
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement