Animation JavaFX:如何检测按键是否被按下?

Animation JavaFX:如何检测按键是否被按下?,animation,javafx,keyevent,Animation,Javafx,Keyevent,我正在使用时间线,希望将一些按键事件连接到舞台上,从而改变时间线在运行过程中改变属性的方式 我知道如何区分按下的键和我想听的键,但我需要知道如何确定某个键是否刚刚按下过一次(如键入),或者某个键是否被按住了更长的时间,这样我就可以让程序在按住键的时间越长的情况下进行更快的调整。当按下键时,您会不断收到按键事件。您可以计算一行中按同一键的次数: SimpleIntegerProperty aCount = new SimpleIntegerProperty(0); SimpleIntegerPro

我正在使用
时间线
,希望将一些
按键
事件连接到舞台上,从而改变时间线在运行过程中改变属性的方式


我知道如何区分按下的键和我想听的键,但我需要知道如何确定某个键是否刚刚按下过一次(如键入),或者某个键是否被按住了更长的时间,这样我就可以让程序在按住键的时间越长的情况下进行更快的调整。

当按下键时,您会不断收到按键事件。您可以计算一行中按同一键的次数:

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); }
});
下面是一个简单的测试应用程序:

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);
    }
}

因此,每次我使用密钥事件时,如果仍然按住密钥,它会再次触发吗?很高兴知道,谢谢。