如何计算用户从5个组合框

时间:2016-07-29 14:39:48

标签: java javafx javafx-8

我已经完成了600行代码并制作了5个组合框我能够显示每个项目的价格但是无法显示这里选择的项目总数是我所做的组合框之一的代码。

    lights.setConverter(new StringConverter<Light>() {
        @Override
        public String toString(Light object) {
            return object.getName();
        }

        @Override
        public Light fromString(String string) {
            return null;
        }
    });



    lights.setItems(FXCollections.observableArrayList
           (new Light ("Incandescent", 5.23),
            new Light ("Halogen", 5.75),
            new Light ("fluorescent",7.29),
            new Light ("Compact fluorescent bulbs",4.83),
            new Light ("LED",4.83)));


    lights.setPromptText("Please select a light");
    lights.setPrefWidth(100);


         lights.valueProperty().addListener((obs, oldVal, newVal) -> {
         String selectionText = "The price for the " + newVal.getName() + " light is : $" + newVal.getPrice();
       lightNamePrice.setText(selectionText);
    });

 private class Light {
    private String name;
    private Double price;

    private Double getPrice() {
        return price;
    }

    private String getName() {
        return name;
    }

    private Light(String name, Double price) {
        this.name = name;
        this.price = price;

    }

}

我这样做对吗? 我需要做些什么才能找到用户用其他4个组合框选择的项目的总成本?

1 个答案:

答案 0 :(得分:1)

使用绑定:

DoubleBinding total = Bindings.createDoubleBinding(() -> {
    double total = 0 ;
    if (lights.getValue() != null) total += lights.getValue().getPrice();
    // similarly for other combo boxes...
    return total ;
}, lights.valueProperty(), otherComboBox.valueProperty() /* etc for other combos*/);

然后你可以做像

这样的事情
totalPriceLabel.textProperty().bind(total.asString());