JavaFX : How to detect if a key is being held down?

6.8k Views Asked by At

I'm working with Timelines and was hoping to hook up some KeyPress events to the stage that could alter the way the timeline changes the properties over the course it runs.

I know how to differentiate between what key was pressed and for what keys I want to listen, but need to know how I can determine if a key has just been pressed once, like typing, or if a key is being held down for a longer period of time, so that I can have the program make more rapid adjustments the longer the key is held down.

1

There are 1 best solutions below

1
On BEST ANSWER

When a key is being held down, you keep on getting KEY_PRESSED events. You can count how many presses of the same key you get in a row:

SimpleIntegerProperty aCount = new SimpleIntegerProperty(0);
SimpleIntegerProperty bCount = new SimpleIntegerProperty(0);

KeyCombination a = new KeyCodeCombination(KeyCode.A);
KeyCombination b = new KeyCodeCombination(KeyCode.B);

scene.setOnKeyPressed(ke -> {
    aCount.set(a.match(ke) ? aCount.get() + 1 : 0);
    bCount.set(b.match(ke) ? bCount.get() + 1 : 0);
});
scene.setOnKeyReleased(ke -> {
    if(a.match(ke)) { aCount.set(0); }
    else if(b.match(ke)) { bCount.set(0); }
});

Here is a simple test application:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class KeySpeedTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        SimpleIntegerProperty aCount = new SimpleIntegerProperty(0);
        SimpleIntegerProperty bCount = new SimpleIntegerProperty(0);

        KeyCombination a = new KeyCodeCombination(KeyCode.A);
        KeyCombination b = new KeyCodeCombination(KeyCode.B);

        Label aLabel = new Label();
        Label bLabel = new Label();
        aLabel.textProperty().bind(Bindings.concat("  A:  ", aCount));
        bLabel.textProperty().bind(Bindings.concat("  B:  ", bCount));

        HBox root = new HBox(aLabel, bLabel);
        Scene scene = new Scene(root, 300, 250);

        scene.setOnKeyPressed(ke -> {
            aCount.set(a.match(ke) ? aCount.get() + 1 : 0);
            bCount.set(b.match(ke) ? bCount.get() + 1 : 0);
        });
        scene.setOnKeyReleased(ke -> {
            if(a.match(ke)) { aCount.set(0); }
            else if(b.match(ke)) { bCount.set(0); }
        });

        primaryStage.setScene(scene);
        primaryStage.setTitle("Key Speed Test");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}