這可以在Netbeans中可以非常容易地實現, 所有你需要的是拖放JLabel
一個JTextField
和JButton
和調用setText(findExchangeRateAndConvert("NGN", "USD", 150000))
。點擊該按鈕以獲取一種貨幣的文本,並設置JLabel
的結果。
或者
public class NewClass{
private JFrame frame; //MainFrame
//Text fields to take input
private JTextField euro;
private JTextField dollar;
//Buttons to convert
private JButton toUSD;
private JButton toEuro;
private JLabel euroLabel;
private JLabel dollarLabel;
public static void main(String[]args){
frame = new JFrame("Currency Conversion");
//init method call
init();
toUSD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
dollar.setText(euro.getText().toString()+" -> " + findExchangeRateAndConvert("EUR", "USD",Integer.parseInt(euro.getText().toString())));
} catch(Exception e) {
e.printStackTrace();
}
}
});
toEuro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
euro.setText(dollar.getText().toString()+" -> " + findExchangeRateAndConvert("USD", "EUR",Integer.parseInt(dollar.getText().toString())));
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
/**
*init method
**/
private void init(){
euro = new JTextField(30);
dollar = new JTextField(30);
euroLabel = new JLabel(10);
dollarLabel = new JLabel(10);
toUSD = new JButton("To USD");
toEuro = new JButton("To Euro");
}
/**
*Method to set the layout and show the Frame
**/
private void showFrame(){
//Set the layout of the JFrame
frame.setLayout(new FlowLayout());
frame.setBounds(50, 120, 200, 20);
//Add the elements
frame.add(euro);
frame.add(toUSD);
frame.add(dollar);
frame.add(toEuro);
//Show the JFrame
frame.pack();
frame.setVisible(true);
}
/**
*your findExchangeRateAndConvert method
**/
private static Double findExchangeRateAndConvert(String from, String to, int amount) {
try {
//Yahoo Finance API
URL url = new URL("http://finance.yahoo.com/d/quotes.csv?f=l1&s="+ from + to + "=X");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = reader.readLine();
if (line.length() > 0) {
return Double.parseDouble(line) * amount;
}
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
一方面,JFrame中不會在Android上工作... –
@George西姆斯公司的NetBeans,u能幫助,它只是一個貨幣轉換器 – chopsticks
@chopsticks爲什麼你把它標記爲Android? –