[英]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.