2013-05-03 29 views
1

我想制作一个简单的java货币转换器图形用户界面。到目前为止,我有这样的:(4份)Java货币转换器图形用户界面

enter image description here

我将如何在jcombbox每个项目设定的值,这样我可以用它们来计算转换(例如每一种货币。)?

这里的第一部分(1个组合框):一个可能的解决方案的

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(); 
} 
} 
+0

我以为你已经做了一个GUI删除C来自代码的并发问题,“Java并发转换器”。 – arynaq 2013-05-03 20:14:25

回答

1

建议:

  • 我将创建一个货币类,一个有一个String currencyName场和双currencyRate保持其比率与某些标准相比较的字段。
  • 我会用货币对象填充我的JComboBox模型。
  • 我给JCOmboBox一个单元格渲染器,以便它显示货币名称。
  • 我愿意付出我的GUI中的“转换”的JButton
  • 在该按钮的动作,我会通过调用getSelectedItem()提取两个组合框中选择货币,并会利用它们来计算一个答案。
  • 在尝试计算之前,确保所选项目都不为空。
  • 或者,这可以通过一个ActionListener来完成添加到两个组合框,但同样我首先要确保所选择的值不为空或所选择的指数并非-1。
2

也许尝试使用Map(例如HashMap中)而不是数组?关键将是货币名称,价值将是货币的价值。因此,而不是:

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

我想使它:

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... 
} 
1

创建Currency类,它包含一个双值,它是货币的价值(您选择如何计算这些)。

有货币的toString()什么样的回报应显示在组合框中,如“USD - 美国美元”。

现在确保您的JComboBox使用泛型,所以当你打电话getSelectedItem()你不必将它转换为Currency,为new JComboBox<Currency>()。如果你有Java 6的项目组仍然可以使用的JComboBox仿制药,尽管这是在Java 7中添加的,因为一些所谓的类型擦除花哨的东西。查看它的细节。

2

唯一的评论,我对汇率看法

  1. 定义货币对,在默认情况下是有基础和可变货币

  2. 为Exange率

  3. 定义买入定义/出售

  4. 定义为基地/变数

  5. (把所有我点起来),那么有四种可能的组合

    • 买入基地(1.31欧元1,000.-)

    • 销售基地(EUR 1,000.- 1.31)

    • 买变量(美元1,000.-在1.311)

    • (在1.311美元1,000.-)出售可变

  6. 英镑/美元有反转的计算方法

1

我没有看到太多的点击您所提供的网址,所以我的热知道这将是一个精确配合,但像这样的东西通常可以用Java enum来解决。特别是,你可以使用类似下面的存储转换的字符串和费率(请注意,我选择了任意转换率 - 代替这些实际增长率):

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

} 

然后,你可以把它们添加到您的组合框这样:

for(Currency currency : Currency.values()) { 
    CurrencyBox.addItem(currency); 
} 
+0

您不想将转换率硬编码为枚举,因为它们意图波动且会波动。最好创建一个没有转换率的枚举,然后使用EnumMap来保存与每个转换枚举项目关联的比率。 – 2013-05-03 20:08:25

+0

我不一定同意这一点。这一切都取决于该计划的规格。如果它的目的是保持最新的转换率,那么我会同意你的看法。但是在看这个时,我并没有认为是这种情况,而是选择提供一个静态解决方案。但是为了清楚起见,让我们问一下@ user2348024,在不重建项目的情况下(即在运行时从配置文件中读取速率还是通过Web服务等检索速率),转换率是否需要更改? – paulk23 2013-05-03 20:17:08

+0

可能。我已经投票支持你,因为我喜欢你使用枚举的一般建议。 – 2013-05-03 20:21:11

0

基本上,我明白"Exchange rate"的方式是,多少它的成本为交换一个货币。

对我而言,这意味着有必要将一种货币与另一种货币相关联。这可以是一个“货币对

除了一些以前的建议(例如使用枚举),作为一个蛮力,与汇率相关联的货币对可用于转换。

例如(请注意,下面的代码将需要适当的验证和尺度/舍入):

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


} 
1
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     
} 

尝试此代码 我已采取印度卢比作为碱 它可以转换 印第安卢比 美元 英镑 日元 欧元