按下按钮时我无法循环播放,按下按钮时停止循环播放。
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");
}
});
答案 0 :(得分:2)
时间轴最适合此类循环
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();
}