JavaFX 2.0 + FXML - Strange Search Behavior

I want to find a VBox node in a scene loaded FXMLoaderthanks Node#lookup(), but I get the following exception:

java.lang.ClassCastException: com.sun.javafx.scene.control.skin.SplitPaneSkin$Content cannot be cast to javafx.scene.layout.VBox

The code:

public class Main extends Application {  
    public static void main(String[] args) {
        Application.launch(Main.class, (java.lang.String[]) null);
    }
    @Override
    public void start(Stage stage) throws Exception {
        AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("test.fxml"));
        Scene scene = new Scene(page);
        stage.setScene(scene);
        stage.show();

        VBox myvbox = (VBox) page.lookup("#myvbox");
        myvbox.getChildren().add(new Button("Hello world !!!"));
    }
}

Fxml file:

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" >
  <children>
    <SplitPane dividerPositions="0.5" focusTraversable="true" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
      <items>
        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
        <VBox fx:id="myvbox" prefHeight="398.0" prefWidth="421.0" />
      </items>
    </SplitPane>
  </children>
</AnchorPane>

I would like to know:
1. Why SplitPaneSkin$Contentdoes the search method return a rather than VBox?
2. How can I get in VBoxanother way?

Thanks in advance

+5
source share
2 answers
  • SplitPane places all elements in separate stacks of the stack (set as SplitPaneSkin$Content). For an unknown reason, FXMLLoader assigns them the same identifier as the root. You can get the VBox that you need with the following utility method:

    public <T> T lookup(Node parent, String id, Class<T> clazz) {
        for (Node node : parent.lookupAll(id)) {
            if (node.getClass().isAssignableFrom(clazz)) {
                return (T)node;
            }
        }
        throw new IllegalArgumentException("Parent " + parent + " doesn't contain node with id " + id);
    }
    

    and use it as follows:

    VBox myvbox = lookup(page, "#myvbox", VBox.class);
    myvbox.getChildren().add(new Button("Hello world !!!"));
    
  • Controller :

    @FXML
    VBox myvbox;
    
+7

VBox - FXMLLoader # getNamespace(). :

VBox myvbox = (VBox)fxmlLoader.getNamespace().get("myvbox");

, FXMLLoader load(), :

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("test.fxml"));
AnchorPane page = (AnchorPane) fxmlLoader.load();
+9

All Articles