gpt4 book ai didi

按下按钮时 javafx 循环

转载 作者:行者123 更新时间:2023-12-02 02:40:00 28 4
gpt4 key购买 nike

我无法在按下按钮时使其循环,并在释放按钮时停止循环。

btnUp.pressedProperty().addListener((observable, wasPressed, pressed) -> {
System.out.println("changed");
if (pressed) {
System.out.println("pressed");
while(btnUp.isArmed()){
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
//moveflag = false;
System.out.println("pressed");
}
} else {
System.out.println("released");
}
});

最佳答案

  1. 不要在 UI 操作中使用 Thread.sleep(),它会阻止所有 UI 绘制
  2. 不要在changelistener中使用while,只需有一个单独的循环来检查按钮的状态
  3. 时间线最适合此类循环

    public void start(Stage stage) {
    Button btn = new Button("Press me");

    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), (ActionEvent event) -> {
    // this code will be called every second
    System.out.println(btn.isPressed() ? "pressed" : "released");
    }));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();


    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(new StackPane(btn), 300, 250);
    stage.setTitle("Hello World!");
    stage.setScene(scene);
    stage.show();

    }

关于按下按钮时 javafx 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655607/

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