Search code examples
javafxcastingchildren

Howto cast List items from VBox.getChildren() in JavaFX


I have a VBox in which many nodes of type Buttonare added.

private final VBox vbox = new VBox();

private final Button b1= new Button("1");
private final Button b2= new Button("2");
private final Button b3= new Button("3");
private final Button b4= new Button("4");

vbox.getChildren().addAll(b1,b2,b3,b4);


Is there a way to cast its child items to Button type.

I need something like this:

ObservableList<Button> children = (ObservableList<Button>) vbox.getChildren();

Solution

  • Yes this is possible, if you use the raw type.

    ObservableList<Button> children = (ObservableList)vbox.getChildren();
    

    Note however, that this can easily lead to ClassCastExceptions at runtime, if the types are incorrect or the child list hardcodes the parameter type for a parameter that depends on the type parameter.