Insert FXML into Scroll Pane and pass data to controller

Asked

Viewed 148 times

0

My system consists of a main screen, which has a scroll-pane that I’m populating with a list of other FXML scenes, code from which I took an example on the internet, follows the code:

@FXML
private Label label;

@FXML
private VBox pnl_scroll;

@FXML
private void handleButtonAction(MouseEvent event) {
    refreshNodes();
}

@Override
public void initialize(URL url, ResourceBundle rb) {

    refreshNodes();
}

private void refreshNodes() {
    pnl_scroll.getChildren().clear();

    Node[] nodes = new Node[15];

    for (int i = 0; i < 10; i++) {
        try {
            nodes[i] = (Node) FXMLLoader.load(getClass().getResource("Item.fxml"));
            pnl_scroll.getChildren().add(nodes[i]);

        } catch (IOException ex) {
            Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

The problem is, I need to set the data for each scroll-pane.fxml item before adding it, how can I do this?

Thank you!

1 answer

0

You can take the controller of these views as follows:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Item.fxml"));
ItemController controller = loader.getController();
Node root = loader.load();

With this you can call their methods through the variable "controller".

Another thing you can do is use "fx:include" right in the ". fxml" file. I tried to insert them by Scene Builder but never could, despite that after you include them in the file Scene Builder already shows your main view with the others included. This way in the file would look like this:

<VBox prefHeight="200.0" prefWidth="100.0">
    <children>
        <fx:include fx:id="itemId" source="Item.fxml"/>
    </children>
</VBox>

To access the controller in this view, for example, just declare a variable with the Node id plus the word "Controller" at the end. I would be so in this case:

@FXML
private AchorPane itemId;

@FXML
private ItemController itemIdController;

For more information about you can access this link.

  • At first, I’m getting access to my controller’s methods. I made a test method in the item’s controller, which writes on the console, but gives Nullpointerexception at the time of execution.

  • I’m already able to access the methods of the other controller, but I can’t set the values of the Labels, even creating getters and setters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.