Java Convertisseur de Devises GUI


J'essaie de créer une interface GRAPHIQUE simple pour le convertisseur de devises java. Jusqu'à présent, j'ai ceci: (4 parties)

entrez la description de l'image ici

Comment pourrais-je définir les valeurs pour chaque élément dans la jcombbox (ex. chaque devise) afin que je puisse les utiliser pour calculer la conversion?

Voici la première partie (1 combobox):

import java.awt.*;
import java.awt.event.*; 
import javax.swing.*;
public class test extends JPanel
{
private JPanel panel;
private JLabel messageLabel;
private JTextField USDTextField;
private JPanel CurrencyPanel;         
private JComboBox CurrencyBox;       
private String[] Currency  = { "USD - United States Dollar",
                 "GBP - Great Britain Pound", "AUD - Australian Dollar",
                 "EUR- Euro"};
public currency1()
{
  setLayout(new BorderLayout(4,1));
  buildCurrencyPanel();
  add(CurrencyPanel, BorderLayout.CENTER);
  setVisible(true);
  setBorder(BorderFactory.createTitledBorder("Select currency"));

}
private void buildCurrencyPanel()
{
  CurrencyPanel = new JPanel();
  CurrencyBox = new JComboBox(Currency);
  CurrencyPanel.add(CurrencyBox);
}
 public static void main(String[] args)
{
   new currency1();
}
}
Author: Zyerah, 2013-05-03

7 answers

Peut-être essayer d'utiliser Map (par exemple HashMap) au lieu d'un tableau? La clé serait un nom de monnaie et la valeur serait la valeur de la devise. Donc au lieu de:

private String[] Currency  = { "USD - United States Dollar",
                 "GBP - Great Britain Pound", "AUD - Australian Dollar",
                 "EUR- Euro"};

Je le ferais:

private Map<String, Double> Currency = new HashMap<>();
//This is an initialization block
{
   Currency.put("USD - United States Dollar", 4.44);
   Currency.put("GBP - Great Britain Pound", 5.55);
   //and so on...
}
 2
Author: Michał Tabor, 2013-05-03 19:05:15

Seul commentaire, mon point de vue sur le convertisseur de devises

  1. Définition pour les paires de devises, par défaut existe-t-il une Devise de base et une Devise variable

  2. Définitions du taux Exange

  3. Définition pour Acheter / Vendre

  4. Définition de Base/Variable

  5. (mettre tous les points a.m. ensemble) alors il y a quatre combinaisons possibles

    • Acheter Base (EUR 1,000.- à 1.31)

    • Base de vente (EUR 1.000.- à 1.31)

    • Acheter Variable (USD 1,000.- à 1.311)

    • Variable de vente (USD 1,000.- à 1.311)

  6. GBP / USD a des méthodes de calculs inverses

 2
Author: mKorbel, 2013-05-03 19:37:46

Suggestions d'une solution possible:

  • Je créerais une classe de devises, une qui a un champ de chaîne currencyName et un champ double currencyRate qui conserve son taux par rapport à une norme.
  • Je remplirais le modèle de mon JComboBox avec des objets de monnaie.
  • Je donnerais au JCOmboBox un moteur de rendu de cellule afin qu'il affiche le nom de la devise.
  • Je donnerais à mon interface graphique un JButton" convert "
  • Dans l'action de ce bouton, j'extrait les devises sélectionnées des deux combo boîtes en appelant getSelectedItem() et les utiliserait pour calculer une réponse.
  • assurez-vous qu'aucun des éléments sélectionnés sont null avant d'essayer de calculer.
  • Ou cela peut être fait via un ActionListener ajouté aux deux zones de liste déroulante, mais encore une fois, je dois d'abord m'assurer que les valeurs sélectionnées ne sont pas null ou que les indices sélectionnés ne sont pas -1.
 1
Author: Hovercraft Full Of Eels, 2013-05-03 19:00:00

Créez une classe Currency qui contient une double valeur qui est la valeur de la devise (vous choisissez comment les calculer).

Demandez au toString() de la devise de renvoyer ce qui devrait être affiché dans la zone de liste déroulante, comme "USD - Dollar des États-Unis".

Maintenant, assurez-vous que votre JComboBox utilise des génériques, de sorte que lorsque vous appelez getSelectedItem() vous n'avez pas à jeter aux Currency, comme dans new JComboBox<Currency>(). Si votre projet est défini sur Java 6, vous pouvez toujours utiliser les génériques JComboBox, même si cela a été ajouté dans Java 7 car de quelque chose de fantaisie appelé type erasure. Regarder pour plus de détails.

 1
Author: Leo Izen, 2013-05-03 19:06:17

Je n'ai pas vu grand-chose en cliquant sur l'URL que vous avez fournie, donc je suis sûr que ce serait un ajustement exact, mais des choses comme celle-ci sont généralement mieux traitées avec Java enums. En particulier, vous pouvez utiliser quelque chose comme ce qui suit pour stocker vos chaînes de conversion et vos taux (notez que]}

public enum Currency {
    USD(1.0,"United States Dollar"),
    GPB(0.9,"Great Britain Pound"),
    AUD(0.8,"Australian Dollar"),
    EUR(0.7,"Euro");

    private double conversionRatio;
    private String description;

    private Currency(double conversionRatio, String description) {
        this.conversionRatio = conversionRatio;
        this.description = description;
    }

    public double getConversionRatio() {
        return conversionRatio;
    }

    public String getDescription() {
        return description;
    }

    public void toString() {
            return new StringBuilder(name()).append(" - ").append(getDescription()).toString();
    }

}

Ensuite, vous pouvez les ajouter à votre liste déroulante comme ceci:

for( Currency currency : Currency.values() ) {
     CurrencyBox.addItem(currency);
}
 1
Author: paulk23, 2013-05-03 19:58:27
package convert;

public class CConverter extends javax.swing.JFrame {

    // Currency Values {Rupee,Dollar,Pound,Yen,Euro} 
double curr1[] = {0,1,0.015,0.012,1.67,0.014};
double curr2[] = {0,1,0.015,0.012,1.67,0.014}; 

/**
 * Creates new form CConverter
 */
public CConverter() {
    initComponents();
}

/**
 * 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() {

    jLabel1 = new javax.swing.JLabel();
    jcmbCurrency1 = new javax.swing.JComboBox<>();
    jcmbCurrency2 = new javax.swing.JComboBox<>();
    jtxtAmount = new javax.swing.JTextField();
    jlblConversion = new javax.swing.JLabel();
    jbtnConvert = new javax.swing.JButton();
    jbtnReset = new javax.swing.JButton();
    jtxtConversion = new javax.swing.JTextField();
    jbtnExit = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    jLabel1.setText("Currency Converter");

    jcmbCurrency1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose One", "INDIA Rupee", "US Dollar", "UK Pound", "JAPAN Yen", "Euro" }));

    jcmbCurrency2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose Other", "INDIA Rupee", "US Dollar", "UK Pound", "JAPAN Yen", "Euro" }));

    jtxtAmount.setText("Amount");

    jlblConversion.setText("Conversion");

    jbtnConvert.setText("CONVERT");
    jbtnConvert.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jbtnConvertActionPerformed(evt);
        }
    });

    jbtnReset.setText("RESET");
    jbtnReset.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jbtnResetActionPerformed(evt);
        }
    });

    jtxtConversion.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    jtxtConversion.setForeground(new java.awt.Color(0, 0, 204));
    jtxtConversion.setText("Converted Value");

    jbtnExit.setText("Exit");
    jbtnExit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jbtnExitActionPerformed(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()
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jLabel1)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jbtnConvert)
                    .addGap(18, 18, 18)
                    .addComponent(jbtnReset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addComponent(jcmbCurrency1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jcmbCurrency2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jtxtAmount)
                .addComponent(jlblConversion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jtxtConversion))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGroup(layout.createSequentialGroup()
            .addGap(158, 158, 158)
            .addComponent(jbtnExit)
            .addContainerGap(191, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(jLabel1)
            .addGap(28, 28, 28)
            .addComponent(jcmbCurrency1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jcmbCurrency2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jtxtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(38, 38, 38)
            .addComponent(jlblConversion)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jtxtConversion, 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(jbtnConvert)
                .addComponent(jbtnReset))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jbtnExit)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

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

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


    double amt = Double.parseDouble(jtxtAmount.getText());

    int obj1 = jcmbCurrency1.getSelectedIndex();
    int obj2 = jcmbCurrency2.getSelectedIndex();

    if (obj1 == obj2){
        String samecur = "Both the currencies cannot be the same";
        jtxtConversion.setText(samecur);
    }
    else {
        double res = (amt/curr1[obj1])*curr2[obj2];

        String conv = String.format("%.2f",res);
        jtxtConversion.setText(conv);
    }

}                                           

private void jbtnResetActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    jtxtAmount.setText(null);
    jtxtConversion.setText(null);
    jcmbCurrency1.setSelectedIndex(0);
    jcmbCurrency2.setSelectedIndex(0);
}                                         

private void jbtnExitActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    System.exit(0);
}                                        

/**
 * @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(CConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CConverter.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() {
            new CConverter().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JButton jbtnConvert;
private javax.swing.JButton jbtnExit;
private javax.swing.JButton jbtnReset;
private javax.swing.JComboBox<String> jcmbCurrency1;
private javax.swing.JComboBox<String> jcmbCurrency2;
private javax.swing.JLabel jlblConversion;
private javax.swing.JTextField jtxtAmount;
private javax.swing.JTextField jtxtConversion;
// End of variables declaration                   
}

Essayez ce code j'ai pris la roupie indienne comme base il peut convertir roupie indienne dollar us livre sterling yen japonais euro

 1
Author: Siddharth ST, 2017-01-28 16:12:28

Fondamentalement, la façon dont je le comprends "taux de Change" est, combien il en coûte d'échanger une devise contre une autre.

, Pour moi, cela signifie qu'il est nécessaire d'associer une devise à une autre. Cela peut être une "Paire de devises "

En plus de certaines des suggestions précédentes (par exemple. En utilisant une énumération), en tant que force brute, une paire de devises associée à un taux de change peut être utilisée pour la conversion.

Par exemple (Notez que le code ci-dessous besoin d'une validation et d'une échelle/arrondi appropriés):

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import static javax.swing.JFrame.EXIT_ON_CLOSE;

public class Main extends JPanel {
    enum Currency {
        USD("United States Dollar"),
        GBR("Great Britain Pound"),
        AUD("Australian Dollar"),
        EUR("Euro");

        private String description;

        Currency(String description) {
            this.description = description;
        }

        @Override public String toString() {
            return this.name() + " - " + this.description;
        }
    }

    class CurrencyPair {
        private final Currency from;
        private final Currency to;

        public CurrencyPair(Currency from, Currency to) {
            this.from = from;
            this.to = to;
        }

        @Override public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            CurrencyPair that = (CurrencyPair) o;
            if (from != that.from) return false;
            return to == that.to;
        }

        @Override public int hashCode() {
            int result = from.hashCode();
            result = 31 * result + to.hashCode();
            return result;
        }
    }

    private final Map<CurrencyPair, BigDecimal> exchangeRates = new HashMap<CurrencyPair, BigDecimal>() {{
        put(new CurrencyPair(Main.Currency.USD, Main.Currency.USD), BigDecimal.valueOf(1));
        put(new CurrencyPair(Main.Currency.AUD, Main.Currency.AUD), BigDecimal.valueOf(1));
        put(new CurrencyPair(Main.Currency.EUR, Main.Currency.EUR), BigDecimal.valueOf(1));
        put(new CurrencyPair(Main.Currency.GBR, Main.Currency.GBR), BigDecimal.valueOf(1));

        put(new CurrencyPair(Main.Currency.USD, Main.Currency.GBR), BigDecimal.valueOf(0.75));
        put(new CurrencyPair(Main.Currency.USD, Main.Currency.AUD), BigDecimal.valueOf(1.33));
        put(new CurrencyPair(Main.Currency.USD, Main.Currency.EUR), BigDecimal.valueOf(0.89));

        put(new CurrencyPair(Main.Currency.EUR, Main.Currency.USD), BigDecimal.valueOf(1.12));
        put(new CurrencyPair(Main.Currency.EUR, Main.Currency.AUD), BigDecimal.valueOf(1.49));
        put(new CurrencyPair(Main.Currency.EUR, Main.Currency.GBR), BigDecimal.valueOf(0.85));

        put(new CurrencyPair(Main.Currency.AUD, Main.Currency.USD), BigDecimal.valueOf(0.74));
        put(new CurrencyPair(Main.Currency.AUD, Main.Currency.EUR), BigDecimal.valueOf(0.67));
        put(new CurrencyPair(Main.Currency.AUD, Main.Currency.GBR), BigDecimal.valueOf(0.57));

        put(new CurrencyPair(Main.Currency.GBR, Main.Currency.USD), BigDecimal.valueOf(1.33));
        put(new CurrencyPair(Main.Currency.GBR, Main.Currency.EUR), BigDecimal.valueOf(1.18));
        put(new CurrencyPair(Main.Currency.GBR, Main.Currency.AUD), BigDecimal.valueOf(1.76));

    }};

    public Main() {
        super(new FlowLayout(FlowLayout.LEADING));

        // Amount
        JTextField amountInput = new JTextField(20);
        JPanel amount = new JPanel();
        amount.add(amountInput);
        amount.setBorder(BorderFactory.createTitledBorder("Enter Ammount"));
        add(amount, BorderLayout.CENTER);

        // From
        JPanel from = new JPanel();
        JComboBox fromOptions = new JComboBox(Currency.values());
        from.add(fromOptions);
        from.setBorder(BorderFactory.createTitledBorder("Select currency"));
        add(from, BorderLayout.CENTER);

        // To
        JComboBox toOptions = new JComboBox(Currency.values());
        JPanel to = new JPanel();
        to.add(toOptions);
        to.setBorder(BorderFactory.createTitledBorder("Convert to"));
        add(to, BorderLayout.CENTER);

        // Convert Action
        JLabel convertText = new JLabel();
        JButton convertCmd = new JButton("Convert");
        convertCmd.addActionListener(convertAction(amountInput, fromOptions, toOptions, convertText));
        JPanel convert = new JPanel();
        convert.add(convertCmd);
        convert.add(convertText);
        add(convert);
    }

    private ActionListener convertAction(
            final JTextField amountInput,
            final JComboBox fromOptions,
            final JComboBox toOptions,
            final JLabel convertText) {

        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // TODO: Needs proper validation
                String amountInputText = amountInput.getText();
                if ("".equals(amountInputText)) { return; }

                // Convert
                BigDecimal conversion = convertCurrency(amountInputText);
                convertText.setText(NumberFormat
                        .getCurrencyInstance(Locale.US)
                        .format(conversion));
            }

            private BigDecimal convertCurrency(String amountInputText) {
                // TODO: Needs proper rounding and precision setting
                CurrencyPair currencyPair = new CurrencyPair(
                        (Currency) fromOptions.getSelectedItem(),
                        (Currency) toOptions.getSelectedItem());
                BigDecimal rate = exchangeRates.get(currencyPair);
                BigDecimal amount = new BigDecimal(amountInputText);
                return amount.multiply(rate);
            }
        };
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new Main());
        frame.setTitle("Currency Thing");
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }


}
 0
Author: razboy, 2016-09-11 14:55:26