简体   繁体   中英

How can I combine a FXML file and a group in JavaFX?

So I made a FXML file for a little game I'm making for school and it has some buttons and labels in it, and it has it's own controller. Now I made a group of rectangles and want to add it to the same scene as the fxml file.

button.getParent().getChildren().add(group);

The code I wrote here doesn't work. Anybody an idea on how to add the group in the fxml file or just render it on the scene?

Rendering the fxml and the group in 2 diffrent scenes does work, so there are no errors.

EDIT:

Application class:

package retris;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author Arno Vandersmissen, Casper Vranken, Rani Vanhoudt
 */
public class Retris extends Application {

    private Stage stage;

    @Override
    public void start(Stage stage) throws Exception {

        this.stage = stage;

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("FXMLRetris.fxml")); 
        Parent root = loader.load();

        FXMLRetrisController controller = loader.getController();

        controller.playMusic();

        stage.setOnCloseRequest(e -> {
            e.consume();
            FXMLConfirmController confirm= new FXMLConfirmController();
            if(confirm.close("Close?")){
                Platform.exit();
            }
        });

        Scene scene = new Scene(root);

        stage.setTitle("Retris");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

A Scene can only display ONE Parent at a time. Whatever you want to display in your GUI would be contained in that Parent . Assuming, as you suggested in the comments, that you want to update that parent at runtime, you need to have a reference to whatever child of the parent that should contain your group of rectangles .

let's say the root element of your fxml file is AnchorPane , and you also want to add the group of rectangles to that root. In your .fxml file you need a fx:id tag <AnchorPane fx:id="myRoot"> this allows you to inject the element to your controller class by use of the @FXML annotation.

public class MyController {
    @FXML private AnchorPane myRoot;

    @FXML private void createAndAddRectangles {
        /**myRoot is already instantiated. you can simply add nodes to it at runtime 
        by using onAction="createAndAddRectangles" tag on a button in your .fxml file.**/
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM