How do you add nodes to an object that is not the main parent (javafx)?


Question

I could not find anything on the topic anywhere i looked. I would like to add a rectangle to my AnchorPane (anchorPaneOne) that is inside my ScrollPane (scrollPane) but whatever i see to do i keep getting errors.

Here is my code:

Main Class:

    package application;

    import javafx.application.Application;
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.control.ScrollPane;
    import javafx.scene.layout.AnchorPane;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;



    public class Main extends Application {
    @FXML
    ScrollPane scrollPane;
    @FXML
    AnchorPane main;
    @FXML
    AnchorPane anchorPaneOne;
public void start(Stage primaryStage) {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
        Scene scene = new Scene(root,600,400);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Stack Overflow Example");
        primaryStage.show();
        Rectangle r = new Rectangle();
        //It will not let me do anchorPaneOne.getChildren().add(r);
    } catch(Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    launch(args);
}
}

Main.fxml:

    <?xml version="1.0" encoding="UTF-8"?>

    <?import javafx.scene.control.*?>
    <?import java.lang.*?>
    <?import javafx.scene.layout.*?>


    <AnchorPane fx:id="main" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <children>
  <ScrollPane fx:id="scrollPane" prefHeight="400.0" prefWidth="600.0">
    <content>
      <AnchorPane fx:id="anchorPaneOne" minHeight="0.0" minWidth="0.0" prefHeight="800.0" prefWidth="585.0" />
    </content>
  </ScrollPane>
  </children>
  </AnchorPane>

Any assistance would be appreciated.
Thanks

1
0
7/20/2014 10:51:55 PM

Accepted Answer

The loader needs to know where to inject the instances to - without the field anchorPaneOne can't be instantiated and remains null. That's done by the controller property which must be set before actually loading the ui:

// create a loader
FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
// set this instance as its controller
loader.setController(this);
// load the ui 
Parent root = loader.load();
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.setTitle("Stack Overflow Example");
primaryStage.show();
Rectangle r = new Rectangle(100, 100);
// now the field is instantiated and can be accessed without NPE 
anchorPaneOne.getChildren().add(r);
2
7/21/2014 10:56:06 AM

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