Folie a deux
Folie a deux

Reputation: 13

javafx looping while button pressed

I am having trouble getting this to loop when the button is pressed, and stop looping when the button is released.

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

Upvotes: 0

Views: 830

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34478

  1. don't use Thread.sleep() inside UI operations, it blocks all UI drawing
  2. don't use while inside changelistener, just have a separate loop which checks button's state
  3. Timelines are best for such loops

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

    }

Upvotes: 2

Related Questions