Is it possible to test in java whether the button is pressed or not?

Question:

Is it possible to test in java whether the button is held down or not, for example, if I hold down the W button, then k = 1, and if I press it, then k = 0? If possible an example. Here is my button code:

if (ke.getCode().getName().equals("W")) {
                k = 1;
            }

                switch (k) {
            case 1:// W
                gc.drawImage(fon, 0, 0, 1280, 720);

                koy = koy - SPEED;
                gc.setFill(Color.BLACK);
                gc.fillOval(kox - 5, koy - 5, kord + 10, kord + 10);

                gc.setFill(Color.YELLOWGREEN);
                gc.fillOval(kox, koy, kord, kord);
                for (int l = 0; l < 26; l++) {
                    if (koy == prom1[l] - kord) {
                        koy = koy + 720 + kord;
                    }
                }
                break;}

Answer:

Yes you can. Catch your event on Scene, Layout-e:

setOnKeyPressed () – When the button is pressed.

setOnKeyReleased () – When the button is released.

And write it something like this:

scene.setOnKeyPressed(event -> {
        if(event.getCode() == KeyCode.W){
            //do_something
        }

scene.setOnKeyReleased(event -> {
        if(event.getCode() == KeyCode.W){
            //do_something
        }
    });
Scroll to Top