我正在制作一个模拟器,其中有一个按钮根据按下的持续时间具有不同的行为。
如果按下按钮少于 3 秒,则不打印任何内容,在 3 到 10 之间,打印 1,大于 10 打印 2。
我应该尝试使用 MouseListener
还是 ActionListener
?任何示例代码都会很棒!谢谢。
最佳答案
监听 pressed 属性的变化:
public class StageTest extends Application{
private long startTime;
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Hold");
Label label= new Label();
btn.pressedProperty().addListener((obs, wPressed, pressed) -> {
if (pressed) {
startTime = System.nanoTime();
label.setText("");
} else {
label.setText("Button was pressed for "+ (System.nanoTime() - startTime) + " nanos");
}
});
Pane root = new VBox(btn, label);
Scene scene = new Scene(root, 300, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch();
}
}
关于java - 检查按下按钮多长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47267369/