How to add node to another node's child in FXML?

微笑、不失礼 提交于 2019-12-11 11:07:26

问题


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();
    }

}

Custom node:

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>

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>

but this adds labels to the custom group. I want to add them to the content pane (VBox) of the custom group.


回答1:


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.

You can add a separate method to add the items to your VBox. Let us consider the methods:

  • setItems() which accepts Nodes adds them to the VBox
  • getItems() which returns the ObservableList<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>

This FXML adds the new Button inside the VBox.



来源:https://stackoverflow.com/questions/30595320/how-to-add-node-to-another-nodes-child-in-fxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!