以下是一个JavaFX程序,它可以通过连接到公共API获取实时的货币汇率并进行在线换算。
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
public class CurrencyConverter extends Application {
private Map<String, Double> rates = new HashMap<>();
@Override
public void start(Stage primaryStage) throws Exception {
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
gridPane.setPadding(new Insets(10, 10, 10, 10));
Label fromLabel = new Label("从:");
ComboBox<String> fromComboBox = new ComboBox<>();
fromComboBox.setEditable(false);
fromComboBox.getItems().addAll("USD", "EUR", "GBP", "CNY", "JPY", "KRW", "AUD", "CAD", "CHF", "HKD");
fromComboBox.getSelectionModel().selectFirst();
gridPane.addRow(0, fromLabel, fromComboBox);
Label toLabel = new Label("到:");
ComboBox<String> toComboBox = new ComboBox<>();
toComboBox.setEditable(false);
toComboBox.getItems().addAll("USD", "EUR", "GBP", "CNY", "JPY", "KRW", "AUD", "CAD", "CHF", "HKD");
toComboBox.getSelectionModel().selectLast();
gridPane.addRow(1, toLabel, toComboBox);
Label amountLabel = new Label("金额:");
TextField amountTextField = new TextField();
amountTextField.setPromptText("请输入要转换的金额");
gridPane.addRow(2, amountLabel, amountTextField);
Label resultLabel = new Label("转换结果:");
Label resultValueLabel = new Label("");
gridPane.addRow(3, resultLabel, resultValueLabel);
Button convertButton = new Button("换算");
convertButton.setOnAction(event -> {
String fromCurrency = fromComboBox.getSelectionModel().getSelectedItem();
String toCurrency = toComboBox.getSelectionModel().getSelectedItem();
double amount = Double.parseDouble(amountTextField.getText().trim());
double fromRate = rates.get(fromCurrency);
double toRate = rates.get(toCurrency);
double result = amount / fromRate * toRate;
resultValueLabel.setText(String.format("%.2f %s = %.2f %s",
amount, fromCurrency, result, toCurrency));
});
gridPane.addRow(4, convertButton);
Scene scene = new Scene(gridPane, 400, 200);
primaryStage.setTitle("货币换算");
primaryStage.setScene(scene);
primaryStage.show();
// 在JavaFX应用中使用线程
Thread thread = new Thread(() -> {
while(true) {
try {
updateRates();
Thread.sleep(60000); // 每60秒更新一次汇率
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
});
thread.setDaemon(true);
thread.start();
}
private void updateRates() throws IOException {
URL url = new URL("https://api.exchangeratesapi.io/latest");
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
String json = response.toString();
rates.clear();
rates.put("EUR", 1.0);
Map<String, Object> map = new ObjectMapper().readValue(json, Map.class);
Map<String, Double> ratesMap = (Map<String, Double>) map.get("rates");
for (Map.Entry<String, Double> entry : ratesMap.entrySet()) {
rates.put(entry.getKey(), entry.getValue());
}
}
}
public static void main(String[] args) {
launch(args);
}
}
在该程序中,用户可以选择要转换的货币类型、输入要转换的金额,然后点击“换算”按钮进行在线换算。该程序每60秒更新一次实时汇率,保证换算的准确性。
在JavaFX应用程序中使用线程需要注意线程的执行顺序以及线程的安全性,避免出现UI界面卡死或者数据不一致的问题。