【发布时间】:2021-07-25 22:11:42
【问题描述】:
我创建了一个自定义组件,它基本上是一个包含更多组件的 vbox。但是,当我将它包含在 HomeView.fxml 中时,组件的子项无处可见。每个单独的内部组件都是 null,导致 HomeController 上的绑定部分出现 NullPointerException。我错过了什么?
HomeView.fxml
<StackPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="views.home.HomeController">
<BorderPane>
<center>Placeholder</center>
</BorderPane>
<SidePane fx:id="sidePane" maxWidth="200.0" prefWidth="200.0" style="-fx-background-color: cyan;" translateX="200.0" StackPane.alignment="CENTER_RIGHT" />
</StackPane>
HomeController.java
public class HomeController implements Initializable {
private final HomeViewModel viewModel;
@FXML private SidePane sidePane;
public HomeController(HomeViewModel viewModel) {
this.viewModel = viewModel;
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
// Bind side pane - NullPointerException here, that's why it is commented out
// sidePane.imageProperty().bindBidirectional(viewModel.selectedPlatform().image());
// sidePane.nameProperty().bindBidirectional(viewModel.selectedPlatform().name());
// sidePane.identifierProperty().bind(viewModel.selectedPlatform().id().asString());
}
}
SidePane.fxml
<fx:root type="javafx.scene.layout.Region"
fx:controller="viewscomponents.sidepane.SidePane"
xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
prefWidth="200" maxWidth="200">
<childrenUnmodifiable>
<VBox>
<ImageView fx:id="image" />
<Label text="Name:" />
<TextField fx:id="name" />
<HBox>
<Label alignment="BOTTOM_RIGHT" text="id: " />
<Label fx:id="id" />
</HBox>
</VBox>
</childrenUnmodifiable>
</fx:root>
SidePane.java
public class SidePane extends Region {
@FXML private ImageView image;
@FXML private TextField name;
@FXML private Label id;
public ObjectProperty<Image> imageProperty() {
return image.imageProperty();
}
public StringProperty nameProperty() {
return name.textProperty();
}
public StringProperty identifierProperty() {
return id.textProperty();
}
}
【问题讨论】:
-
minimal reproducible example 请.. 包括导入和应用
-
你永远不会在任何地方加载
SidePane.fxml。在documentation 中查看此模式的示例
标签: java javafx components