Java 货币转换器 GUI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16365794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Currency Converter GUI
提问by user2348024
I'm trying to make a simple java currency converter GUI. So far I have this :(4 parts)
我正在尝试制作一个简单的 java 货币转换器 GUI。到目前为止,我有这个:(4 部分)
How would I set the values for each item in the jcombbox (ex. each currency) so that I can use them to calculate the conversion?
我将如何设置 jcombbox 中每个项目的值(例如每种货币),以便我可以使用它们来计算转换?
Here's the first part (1 combobox):
这是第一部分(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();
}
}
回答by Micha? Tabor
Maybe try using Map (e.g. HashMap) instead of an array? The key would be a currency name and the value would be currency's value. So instead of:
也许尝试使用 Map(例如 HashMap)而不是数组?键是货币名称,值是货币的值。所以而不是:
private String[] Currency = { "USD - United States Dollar",
"GBP - Great Britain Pound", "AUD - Australian Dollar",
"EUR- Euro"};
I would make it:
我会做到:
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...
}
回答by mKorbel
only comment, my view about Currency Converter
仅评论,我对货币转换器的看法
definition for Currency Pairs, by default is there Base and Variable Currency
definitions for Exange Rate
definition for Buy/Sale
definition for Base/Variable
(put all a.m. points together) then there are four possible combinations
buy Base (EUR 1,000.- at 1.31)
sell Base (EUR 1,000.- at 1.31)
buy Variable (USD 1,000.- at 1.311)
sell Variable (USD 1,000.- at 1.311)
GBP/USD has reverse calculations methods
货币对的定义,默认情况下有基础和可变货币
汇率的定义
买/卖的定义
基数/变量的定义
(将所有 am 点放在一起)则有四种可能的组合
购买基础 (EUR 1,000.- at 1.31)
卖出 Base (EUR 1,000.- at 1.31)
买入 Variable (USD 1,000.- at 1.311)
卖出变量 (USD 1,000.- at 1.311)
英镑/美元有反向计算方法
回答by paulk23
I didn't see much in clicking on the URL you provided, so I'm hot sure if this would be an exact fit, but things like this are usually best addressed with Java enum
s. In particular you could use something like the following to store your conversion strings and rates (note that I picked arbitrary conversion rates - substitute the real rates for these):
我在单击您提供的 URL 时没有看到太多内容,因此我很确定这是否完全合适,但通常最好使用 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();
}
}
Then you could add these to your combobox like this:
然后你可以像这样将这些添加到你的组合框中:
for( Currency currency : Currency.values() ) {
CurrencyBox.addItem(currency);
}
回答by Siddharth ST
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
}
Try this code i have taken indian rupee as the base it can convert indian rupee us dollar british pound japanese yen euro
试试这个代码,我以印度卢比为基础,它可以转换印度卢比美元英镑日元欧元
回答by Leo Izen
Create a Currency
class that contains a double value which is the currency's value (you choose how to calculate these).
创建一个Currency
包含作为货币价值的双精度值的类(您可以选择如何计算这些值)。
Have the currency's toString()
return what should be displayed in the combo box, such as "USD - United States Dollar".
让货币toString()
返回组合框中应该显示的内容,例如“USD - United States Dollar”。
Now make sure your JComboBox
uses generics, so when you call getSelectedItem()
you don't have to cast it to Currency
, as in new JComboBox<Currency>()
. If you've got your project set on Java 6 you can still use JComboBox generics, even though that was added in Java 7 because of some fancy thing called type erasure. Look it up for details.
现在确保您JComboBox
使用泛型,因此当您调用时,getSelectedItem()
您不必将其强制转换为Currency
,如new JComboBox<Currency>()
. 如果你的项目是在 Java 6 上设置的,你仍然可以使用 JComboBox 泛型,即使它是在 Java 7 中添加的,因为一些叫做类型擦除的奇特东西。详情请查查。
回答by Hovercraft Full Of Eels
Suggestions of a possible solution:
可能的解决方案的建议:
- I would create a Currency class, one that has a String currencyName field and a double currencyRate field that holds its rate compared to some standard.
- I'd fill my JComboBox's model with objects of Currency.
- I'd give the JCOmboBox a cell renderer so that it shows the Currency name.
- I'd give my GUI a "convert" JButton
- In that button's action, I'd extract the selected Currencies from both combo boxes by calling
getSelectedItem()
and would use them to calculate an answer. - Make sure that neither of the selected items are null before trying to calculate.
- Or this can be done via an ActionListener added to both combo boxes, but again I'd first have to make sure that the selected values are not null or that the selected indices are not -1.
- 我会创建一个 Currency 类,它有一个 StringcurrencyName 字段和一个 doublecurrencyRate 字段,与某个标准相比,它保持其汇率。
- 我会用货币对象填充我的 JComboBox 模型。
- 我会给 JCOmboBox 一个单元格渲染器,以便它显示货币名称。
- 我会给我的 GUI 一个“转换”JButton
- 在该按钮的操作中,我将通过调用从两个组合框中提取选定的货币,
getSelectedItem()
并使用它们来计算答案。 - 在尝试计算之前,请确保所选项目均不为空。
- 或者这可以通过添加到两个组合框的 ActionListener 来完成,但我首先必须确保所选值不为空或所选索引不为 -1。
回答by razboy
Basically, the way I understand "Exchange rate"is, how much it costs to exchange one currency for another.
基本上,我理解“汇率”的方式是,将一种货币兑换成另一种货币的成本是多少。
To me, that means that there is a need to associate one currency with another. This can be a "Currency Pair"
对我来说,这意味着需要将一种货币与另一种货币联系起来。这可以是“货币对”
In addition to some of the previous suggestions (eg. Using an enum), as a brute force, a currency pair associated to an exchange rate can be used for the conversion.
除了之前的一些建议(例如使用枚举)之外,作为一种蛮力,可以使用与汇率相关的货币对进行转换。
For example (Note that the code below will need proper validation and scale/rounding):
例如(请注意,下面的代码需要适当的验证和缩放/四舍五入):
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);
}
}