Question

I want to draw a canvas in a class that extends Scene. This Scene should be displayed when I press a button on a Scene which is created within a class "GUI" extending Application.

Problem: I don't get it how to use the "parent" parameter from the Scene constructor. So I am not able to display the content of the Scene.

When I use:

Scene gameScene = new GameScene(root,800,600);

I'll get an error, because root is already set as a root for another Scene.

With game instead of root everything compiles fine, and the Scene ist displayed, but nothing of the content of the Scene is showing.

In the GameScene class I've tried to use two different types of displaying content.

  1. set an image for the ImageView mapView (I don't know to which node I've to add the ImageView as a child {something like parent.getChildren().add(mapView) doesn't work} )
  2. trying to draw on a Canvas. (Same problem as above. Where do I add this Canvas?)

The GUI class:

public class GUI extends Application {
    public static void main(String[] args) { launch(args); }

    public void start(Stage primaryStage){
        StackPane root = new StackPane();

        Group game = new Group();
        root.getChildren().add(game);
        Scene gameScene = new GameScene(game,800,600);

        Button btn = new Button();
        btn.setText("Start Game");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                primaryStage.setScene(gameScene);
                primaryStage.show();
            }
        });

        root.getChildren().add(btn);

        primaryStage.setScene(new Scene(root, 650,450));
        primaryStage.show();
    }
}

And the GameScene class:

public class GameScene extends Scene {
    private final double WIDTH;
    private final double HEIGHT;
    public Canvas mapCanvas;
    private Map map;

    public GameScene(Parent parent, double x, double y) {
        super(parent, x, y);
        ImageView mapView = new ImageView();
        WIDTH = x;
        HEIGHT = y;
        this.map = new Map((int)x,(int)y);
        mapCanvas = new Canvas(WIDTH,HEIGHT);
        mapView.setImage(map.getImage());

        GraphicsContext graphicsContext = mapCanvas.getGraphicsContext2D();
        draw(graphicsContext);
    }

    public void draw(GraphicsContext gc){
        gc.fillRect(10, 10, 100, 50);
    }
}

PS: Jeah! My first question in this forum. Hello World!

Was it helpful?

Solution

A year later...

replace "Parent" with "Group" or do: (Group)parent

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top