[英]JavaFX: How to set an action to a ComboBox?
ComboBox dropDown = new ComboBox();
dropDown.getItems().addAll("Mexican Peso", "Canadian Dollar", "Euro", "British Pound");
dropDown.setOnAction(e -> dropDownMenu());
private void dropDownMenu(ComboBox dropDown){
}
private void calculatePound() {
double n1 = Double.parseDouble(input.getText());
output.setText(String.format("%.2f", n1*.80));
}
我試圖為組合框中的每個單獨元素調用一個方法。 舉個例子:如果有人選擇了“英鎊”,它將調用我編寫的calculatePound方法並計算英鎊換算。 我沒有做太多的GUI,所以我正嘗試進行更多的練習。
慣用的方法是創建一個封裝所需數據和功能的類,並用其實例填充組合框。
例如,創建一個Currency
類:
public class Currency {
private final double exchangeRate ;
private final String name ;
public Currency(String name, double exchangeRate) {
this.name = name ;
this.exchangeRate = exchangeRate ;
}
public double convert(double value) {
return value * exchangeRate ;
}
public String getName() {
return name ;
}
@Override
public String toString() {
return getName();
}
}
然后做
ComboBox<Currency> dropDown = new ComboBox<>();
dropDown.getItems().addAll(
new Currency("Mexican Peso", 18.49),
new Currency("Canadian Dollar", 1.34),
new Currency("Euro", 0.89),
new Currency("British Pound", 0.77)
);
現在您需要做的就是
dropDown.setOnAction(e -> {
double value = Double.parseDouble(input.getText());
double convertedValue = dropDown.getValue().convert(value);
output.setText(String.format("%.2f", convertedValue));
});
您可以將其他特定於貨幣的信息添加到Currency
類,例如貨幣符號和格式規則等。
請注意,與dropDown.getItems().addAll(...)
貨幣的方法相比,用這種方法添加更多的貨幣要容易得多(您所需要的只是dropDown.getItems().addAll(...)
調用中的另一個new Currency(name, rate)
dropDown.getItems().addAll(...)
帶有字符串的組合框(在開關或if語句中,您將需要其他方法和其他情況)。 這種方法還有許多其他好處。
首先,您需要某種按鈕供用戶在列表中選擇一個項目后單擊。 此按鈕應調用以下方法:
例如:
ComboBox dropDown = new ComboBox();
dropDown.getItems().addAll("Mexican Peso", "Canadian Dollar", "Euro", "British Pound");
Button button = new Button();
button.setOnAction(event -> {
//Call a method to determine which item in the list the user has selected
doAction(dropDown.getValue().toString()); //Send the selected item to the method
});
private void doAction(String listItem) {
switch (listItem) {
case "Mexican Peso": //Action for this item
break;
case "Canadian Dollar": //Action for this item
break;
case "Euro": //Action for this item
break;
case "British Pound": calculatePound();
break;
default: //Default action
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.