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>