0

I have been endeavouring to create an application using FXML which includes a Canvas.

However, when I attempt to obtain the GraphicsContext object in the Controller the application throws a NullPointerException.

In simplified form the application is as follows. If anybody can inform me how to successfully implement the GraphicsContext it will be much appreciated.

Main.java

package sample;

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

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("CanvasDemo");
        primaryStage.setScene(new Scene(root, 450, 480));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java

package sample;

import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;

public class Controller {

    @FXML
    private Canvas canvas;

    GraphicsContext context = canvas.getGraphicsContext2D();
}

sample.fxml

<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.layout.FlowPane?>
<FlowPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
    <Canvas fx:id="canvas" width="400" height="400"></Canvas>
</FlowPane>
Datango
  • 45
  • 4
  • 2
    Just to clarify: Inline instance field initialization occurs at construction time, so the duplicate is relevant despite you not using an explicit constructor. In fact, the compiler essentially folds inline instance field initialization into the constructor(s) (you can research that if you're interested). – Slaw Oct 20 '21 at 16:50

0 Answers0