How to access a child of an object in JavaFX


Let's say I have created an object which can have children and have getChildren() method, f.e. Group(). Then I created an another object which can 'store' children, too, f.e. VBox(). And then again I create yet an another object, f.e. Slider().

So now I add the Slider object to the list of VBox children by calling myVBox.getChildren().add(mySlider);, and then I add the VBox object to the list of Group object. Supose that everything is performed inside a function that returns myGroup object.

Now I'm outside of the function, I have no direct way to access Slider properties, I need to access Group children, get the VBox, then get the Slider from VBox children.

So as far as I understand, I should call myGroup.getChildren().get(0); to get the first child added (which in this case should be the VBox object). Now I need to go deeper, so I should call myGroup.getChildren().get(0).getChildren().get(0);, right?

Unfortunately the object returned by myGroup.getChildren().get(0); does not have a getChildren() method and it's type of Node class, while myGroup.getChildren().get(0).getClass(); returns info that that child is type of VBox.

I'm quite a freshmen in Java, so please, so please, point out my misconceptions.

11/7/2014 11:07:09 PM

Accepted Answer

Assuming you have a Slider inside a VBox with other nodes, and this box is inside a group, you can access the inner slider with getChildren() by casting the resulting node to its type. And before that, make sure you can do this casting by cheking if the node is instance of the specific class with instanceof.

This simple example will help you.

private final Group group = new Group();
private final VBox vbox = new VBox();
private final Button button = new Button("Click");
private final Label label = new Label("Slider Value: ");

public void start(Stage primaryStage) {
    vbox.getChildren().addAll(button, label, new Slider(0,10,4));

        Node nodeOut = group.getChildren().get(0);
        if(nodeOut instanceof VBox){
            for(Node nodeIn:((VBox)nodeOut).getChildren()){
                if(nodeIn instanceof Slider){
                    label.setText("Slider value: "+((Slider)nodeIn).getValue());

    Scene scene = new Scene(group, 300, 250);
11/7/2014 11:17:52 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow