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

标签 animation javafx keyevent

我正在使用Timelines,并希望将一些KeyPress事件连接到舞台,这些事件可以改变时间线在其运行过程中更改属性的方式.

我知道如何区分按下的键和我想听的键,但需要知道如何确定某个键是否刚刚被按下一次(例如打字),或者是否按住了某个键更长的时间,这样我可以让程序做出更快速的调整,按住键的时间越长。

最佳答案

当按住某个键时,您会不断收到 KEY_PRESSED 事件。您可以计算连续按下同一个键的次数:

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

关于animation - JavaFX : How to detect if a key is being held down?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917566/

相关文章:

JavaFX 销毁还是重用按钮?

java - 为什么 `loadFont` 不关闭输入流?我应该关闭它吗?

Java 游戏 - 按下按键

java - Java 应用程序级别的关键事件

iphone - UIPickerView selectRow时触发代码 :inComponent:animated:YES is completed?

javascript - 哪个是最好的 JavaScript 动画框架?

javascript - 如何在 html 5 Canvas 上旋转单个对象?

python - 如何为 seaborn 的热图或相关矩阵制作动画?

java - 以编程方式(与语义方式)将 LongProperty 应用于 TableColumn

javascript - 如何预测 DOM keydown 是否会导致字符输入