我正在编写JavaFX应用程序。我用SceneBuilder 8.2创建了GUI。 我已经放了一些ChoiceBox但是使用Java Type,而不是自定义Type。 它运作良好。 但是使用自定义Type,choiceBox没有实例化,为什么? 代码下方:
public class PelController {
//instanciation is OK
@FXML
private ChoiceBox<PeriodeEnum> fCalculInteret;
//not instanciated at launch
@FXML
private ChoiceBox<DureeChoiceBoxElement> duree;
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
@FXML
private void initialize() {
//fCalculInteret is NOT NULL, automatically instantiated at startup.
fCalculInteret.valueProperty().bindBidirectional(pel.fCalculInteretProperty());
//duree is NULL causing NullPointerException
duree.valueProperty().get().dureeProperty().bindBidirectional(pel.dureeProperty());
}
}
自定义类型:
public class DureeChoiceBoxElement extends ObservableValueBase<DureeChoiceBoxElement> {
private IntegerProperty duree;
public DureeChoiceBoxElement() {
}
public DureeChoiceBoxElement(int duree) {
this.duree = new SimpleIntegerProperty(duree);
}
public IntegerProperty dureeProperty() {
return duree;
}
public Integer getDuree() {
return duree.getValue();
}
@Override
public DureeChoiceBoxElement getValue() {
// TODO Auto-generated method stub
return new DureeChoiceBoxElement(duree.get());
}
public void setDuree(Integer duree) {
this.duree.setValue(duree);
}
@Override
public String toString() {
return duree + " an";
}
}
你能解释为什么这个NullPointer。感谢
答案 0 :(得分:0)
duree.valueProperty().get().dureeProperty().bindBidirectional(pel.dureeProperty());
| |
- &gt; Null可能来自|
public IntegerProperty dureeProperty() {
return duree;
}
返回null,因为默认的构造函数不初始化duree
属性。
1)一种解决方案是将方法修改为:
//lazy
public IntegerProperty dureeProperty() {
if(duree == null) //if duree has not been initialized
duree = new SimpleIntegerProperty();
return duree;
}
或2)您可以更改默认构造函数以初始化private IntegerProperty duree;
属性,尽管解决方案1更好。