0

I have two classes. Rectangle.java and TestRectangle.java. I have to use those two classes to draw a simple 2D rectangle with javafx.fxml.FXML, GraphicsContent2D. Here's what I have so far.

Rectangle.java

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


public class Rectangle {
    @FXML private Canvas canvas;


    public void draw() {
        // get the GraphicsContext, which is used to draw on the Canvas
        GraphicsContext gc = canvas.getGraphicsContext2D();

        // clear canvas for next drawing

        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());

        // draw rectangle

        gc.strokeRect(100, 100, 175, 300);
    }

}

and the second, TestRectangle.java:

TestRectangle.java

public class TestRectangle {
    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle();
        rectangle1.draw();

    }
}

When I run the program, I get the error

Exception in thread "main" java.lang.NullPointerException
    at Rectangle.draw(Rectangle.java:13)
    at TestRectangle.main(TestRectangle.java:4)

I'm brand new to Java, and I'm sure this is a very simple issue. Any help would be appreciated! I also want to do the same for a Sphere and Circle. I'm guessing that I'm missing a declaration somewhere, but can't find what it may be.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • 2
    [mcve] please .. including application, controllers, fxmls and complete stacktrace. That said: you must __load__ the rectangle class (__not__ instantiate) to inject a field that's annotated with @fxml. Unrelated: best not to name custom classes to something already contained in core fx - it's possible, but most certainly will lead to confusion sooner or later. As to _I'm brand new to Java_ first stop - working through basic tutorials on the stuff you are using :) – kleopatra Apr 08 '21 at 08:43
  • 3
    Why don't you start by reading the documentation and start from a working example, e.g., https://docs.oracle.com/javafx/2/get_started/jfxpub-get_started.htm . The pieces you have shown indicate that you have never seen a working JavaFX program before. – mipa Apr 08 '21 at 08:49
  • Why would `canvas` not be null? – James_D Apr 08 '21 at 13:16

0 Answers0