按下按钮时javafx循环

时间:2017-08-12 22:54:31

标签: java javafx

按下按钮时我无法循环播放,按下按钮时停止循环播放。

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 个答案:

答案 0 :(得分:2)

  1. 不要在UI操作中使用Thread.sleep(),它会阻止所有UI绘图
  2. 在changelistener内部不要使用,只需要一个单独的循环来检查按钮的状态
  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();
    

    }