Search code examples
javajavafxroot

Cant add to root in seperate class?


Im working with javaFX and i would like to add a Rectangle object to the game root from a seperate player class. Therfor i created a getRoot function in my Game, and tried adding the rectangle from my player class. Although for some reason it just dosent work.

public class Test {
    public void run() {
        System.out.println("loaded");
        GameScene gameScene = new GameScene();
        gameScene.getRoot().getChildren().add(new Sprite(50,50,50,50, Color.GREEN,"TEST", 1, 0));
    }
}

public class GameScene {

    private Group root = new Group();

    public Scene getScene(){

        Scene scene = new Scene(root, Color.BLACK);
        Test test = new Test();
        test.run();

        return scene;
    }

    public Group getRoot() {
        return root;
    }

}

The gameScene is still just empty when i run it, although the "loaded" string is printed to the console.


Solution

  • Try this for modifying root by another class:

    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    
    public class GameScene extends Application {
    
        private Group root;
        @Override
        public void start(Stage stage) {
            root = new Group();
            stage.setScene(getScene());
            stage.show();
        }
    
        public Scene getScene(){
    
            Scene scene = new Scene(root);
            Test test = new Test();
            test.run(root);
            return scene;
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    
    class Test {
    
        public void run(Group root) {
            root.getChildren().add(new Rectangle(50, 50, Color.BLACK));
        }
    }