java JavaFX自定义节点不呈现子节点
我创建了一个自定义组件,基本上是一个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>
家庭控制器。爪哇
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());
}
}
侧窗格。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>
侧窗格。爪哇
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();
}
}
# 1 楼答案
正如James_D在他的评论中所说,您从未加载自定义控件的fxml文件。此外,我认为它不适用于
Region
,您不应该在fxml文件中指定控制器。它应该是这样工作的:侧窗格。java
侧窗格。fxml