user4402088
user4402088

Reputation: 57

JavaFX: draw canvas by a pressed button through the Controller

I'd like to use a button in order tu get some things drawn on my JavaFX Canvas.

package sample;

import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.scene.control.Label;

public class Controller {

    @FXML
    Canvas canvas1;

    @FXML
    Label label;

    public void onButtonPress(){
        System.out.println("test");
        Canvas canvas1 = new Canvas(300, 250);
        GraphicsContext gc = canvas1.getGraphicsContext2D();
        drawShapes(gc);
        label.setText("test");
    }

    public void drawShapes(GraphicsContext gc) {
        gc.setFill(Color.GREEN);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(5);
        gc.strokeLine(40, 10, 10, 40);
        gc.fillOval(10, 60, 30, 30);
    }
}

When I press the Button, nothing happens. The Canvas in the XML file is defined as follows:

 <Canvas fx:id="canvas1" height="200.0" layoutX="30.0" layoutY="14.0" width="552.0" />

May anyone help me?

Upvotes: 1

Views: 1639

Answers (2)

Bo Halim
Bo Halim

Reputation: 1776

as said, instead of creating a new Canvas you just need to use you annotated one :

@FXML Canvas canvas1;

and finally to draw your shape you need to perform an action from your controller.

Upvotes: 0

James_D
James_D

Reputation: 209714

You're creating a new canvas, and drawing on it, instead of drawing on the canvas that was created in the FXML file.

Remove the line

 Canvas canvas1 = new Canvas(300, 250);

Upvotes: 2

Related Questions