5

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.

Will
  • 3,413
  • 7
  • 50
  • 107

1 Answers1

6

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);
    }
}
Tomas Mikula
  • 6,537
  • 25
  • 39
  • 1
    So effectively every time I consume the key-event, if the key is still held down it fires again? That's good to know thanks. – Will Nov 14 '14 at 04:30