0

I have to use the canvas to draw a curve inside my application, but I think my FXML is not loading the Canvas properly. This is how I initialize it:



    @FXML
    private Canvas canvas;
    private GraphicsContext gc;

    @FXML
    private LineChart<String, Number> chart1;


    @FXML
    public void initialize() {
        canvas = new Canvas(1000, 1000);
        gc = canvas.getGraphicsContext2D();
        gc.setStroke(Color.RED);
        gc.setLineWidth(10);

        canvas.setOnMousePressed(event -> {
            gc.beginPath();
            gc.lineTo(event.getX(), event.getY());
            gc.stroke();
        });

        canvas.setOnMouseDragged(event -> {
            gc.lineTo(event.getX(), event.getY());
            gc.stroke();
        });
    }
}

And in FXML:

<ScrollPane>
      <content>
            <Canvas fx:id="canvas" height="298.0" width="455.0" />
      </content>
</ScrollPane>

This is an example of how it looks now: enter image description here That blue border should be a canvas.

When I comment out the Canvas part from FXML, nothing changes, so that tells me it does not work. What might be wrong?

Lazar Gugleta
  • 115
  • 1
  • 2
  • 14
  • 2
    You are overwriting the original canvas object with canvas = new Canvas(1000, 1000); -- remove that and see if it works. Annotating the field with @FXML initializes it for you – Joe Dec 31 '19 at 17:52
  • 2
    Just a clarification: In order to draw a curve you do not necessarily have to use a Canvas. That is just one of the possible options. Another one would be to just add a Path object to the scenegraph. – mipa Dec 31 '19 at 18:14
  • That worked! Thanks @Joe – Lazar Gugleta Dec 31 '19 at 19:09
  • Ok I did not know that, thanks for the info @mipa – Lazar Gugleta Dec 31 '19 at 19:10

0 Answers0