gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:42:24 24 4
gpt4 key购买 nike

我正在使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com