[JavaFx]这个绑定有什么问题?

时间:2016-12-26 13:40:18

标签: java javafx binding

所以我创建了Instrument类和Controller类。 bindingBidirectional()方法存在很大问题。当我尝试将Combobox属性与AmountProperty类中的Instrument绑定时,它会给我一个错误。

amount.valueProperty().bindBidirectional(instrument.amountProperty());

我在这里做错了什么?

Controller class

public class Controller implements Initializable{

@FXML
private ComboBox<Integer> amount = new ComboBox<>();
ObservableList<Integer> amountOptions = FXCollections.observableArrayList(0, 5, 10, 25, 50);

Instrument instrument = new Instrument();

@Override
public void initialize(URL location, ResourceBundle resources) {

    amount.getItems().addAll(amountOptions);
    //THIS ONE IS NOT WORKING
    amount.valueProperty().bindBidirectional(instrument.amountProperty());

}}

Instrument课程:

public class Instrument {

private IntegerProperty amount = new SimpleIntegerProperty();

public int getAmount() {
    return amount.get();
}

public IntegerProperty amountProperty() {
    return amount;
}

public void setAmount(int amount) {
    this.amount.set(amount);
}
}

1 个答案:

答案 0 :(得分:2)

IntegerPropertyProperty<Number>的实现,而不是Property<Integer>的实现。您的组合框中的valuePropertyProperty<Integer>。因此,您无法直接在两者之间双向绑定,因为类型不匹配。

您可以将组合框更改为ComboBox<Number>,也可以使用IntegerProperty.asObject(),这会创建一个与ObjectProperty<Integer>双向绑定的IntegerProperty

amount.valueProperty().bindBidirectional(
    instrument.amountProperty().asObject());