如何在FXML中将节点添加到另一个节点的子节点? [英] How to add node to another node's child in FXML?
问题描述
我想要获得的示例,用Java代码编写:
Example of what I'd like to get, written in Java code:
public class Main extends Application {
private static Scene scene;
public static void main(String[] args) {
launch(args);
}
@Override
public void init() throws IOException {
// Load root pane from FXML file.
URL url = getClass().getResource("sample.fxml");
StackPane root = FXMLLoader.load(url);
// Create scene for a root node on JavaFX thread.
Platform.runLater(() -> scene = new Scene(root, 600, 400));
}
@Override
public void start(Stage stage) {
stage.setScene(scene);
stage.show();
}
}
自定义节点:
public class CustomGroup extends Group {
private VBox contentPane = new VBox();
public CustomGroup() {
getChildren().add(contentPane);
contentPane.getChildren().add(new Label("First Label"));
contentPane.getChildren().add(new Label("Second Label"));
}
}
FXML:
<StackPane>
<CustomGroup/>
</StackPane>
上面的代码是我想要的例子,但不是在Java中添加标签代码,我想在FXML中添加它们。类似的东西:
The code above is example of what I'd like to get, but instead of adding labels in Java code, I want to add them in FXML. Something like that:
<StackPane>
<CustomGroup>
<Label text="First Label"/>
<Label text="Second Label"/>
</CustomGroup>
</StackPane>
但这会为自定义组添加标签。我想将它们添加到自定义组的内容窗格(VBox)。
but this adds labels to the custom group. I want to add them to the content pane (VBox) of the custom group.
推荐答案
虽然,我不知道你为什么在 CustomGroup
的构造函数中将标签添加到VBox中,我将忽略它并回答您的问题。
Though, I am not sure why you are adding the Labels to your VBox inside the constructor of CustomGroup
, I will ignore it and answer your question.
您可以添加单独的方法将项目添加到 VBox
。让我们考虑一下方法:
You can add a separate method to add the items to your VBox
. Let us consider the methods:
-
setItems()
接受节点
将它们添加到VBox -
getItems()
,返回来自VBox的ObservableList< Node>
setItems()
which acceptsNodes
adds them to the VBoxgetItems()
which returns theObservableList<Node>
from the VBox
CustomGroup
public class CustomGroup extends Group {
private VBox contentPane = new VBox();
public CustomGroup() {
getChildren().add(contentPane);
contentPane.getChildren().add(new Label("First Label"));
contentPane.getChildren().add(new Label("Second Label"));
}
public void setItems(Node...nodes) {
contentPane.getChildren().addAll(nodes);
}
public ObservableList<Node> getItems() {
return contentPane.getChildren();
}
}
FXML
<CustomGroup>
<items>
<Button text="hi"/>
</items>
</CustomGroup>
此FXML在 VBox中添加新Button
。
这篇关于如何在FXML中将节点添加到另一个节点的子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!