How do I draw an image in Canvas, when I press a key with setOnKeyPressed?

117 views Asked by At

I want to draw an image in canvas when I press RIGHT, but I don't know exactly how I should do it.

First I create two variables for later on, then I create my canvas. Then I get the Image I want to draw. I tried getting the key with getCode().equals(KeyCode.Right), but it doesn't work. Please Help.

public class Controller implements Initializable {

    @FXML
    private Canvas canvas;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        double v1 = 0;
        double v2 = 0;

        GraphicsContext gc = canvas.getGraphicsContext2D();
        Image pm = new Image("sample/pacman.png", 20, 20, true, true);


        canvas.setOnKeyPressed(keyEvent -> {
            if (keyEvent.getCode().equals(KeyCode.RIGHT)) {
                gc.drawImage(pm, v1, v2);
            }


        });
    }

}

I expect the image to appear, but instead it's just an empty program.

0

There are 0 answers