【问题标题】:How to make a loop delay? (JavaFX) [duplicate]如何进行循环延迟? (JavaFX)[重复]
【发布时间】:2019-02-21 21:35:25
【问题描述】:
button.setOnAction(new EventHandler<ActionEvent>() {
 @Override
 public void handle(ActionEvent event) {
    while(true) {
    s += 10;
    if((s>height/1.2) || (s == height/1.2)) {
        s = 0;
    }
    label.setLayoutX(s);
    }}});

如何在不停止主 GUI 线程的情况下停止循环?(Thread.sleep(1000) 不起作用)

【问题讨论】:

    标签: java javafx thread-sleep


    【解决方案1】:

    您可以使用JavaFX Timeline。来自here的修改代码。

    下面的应用演示了一种使用Timeline的方法。

    import javafx.animation.KeyFrame;
    import javafx.animation.Timeline;
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    /**
     *
     * @author Sedrick
     */
    public class JavaFXApplication25 extends Application {
    
        Integer s = 0;
    
        @Override
        public void start(Stage primaryStage) {
    
            Label label = new Label(s.toString());
    
            //This Timeline is set to run every second. It will increase s by 10 and set s value to the label.
            Timeline oneSecondsWonder = new Timeline(new KeyFrame(Duration.seconds(1), (ActionEvent event1) -> {
                s += 10;
                label.setText(s.toString());
            }));
            oneSecondsWonder.setCycleCount(Timeline.INDEFINITE);//Set to run Timeline forever or as long as the app is running.
    
            //Button used to pause and play the Timeline
            Button btn = new Button();
            btn.setText("Say 'Hello World'");
            btn.setOnAction((ActionEvent event) -> {
                switch(oneSecondsWonder.getStatus())
                {
                    case RUNNING:
                        oneSecondsWonder.pause();
                        break;
                    case PAUSED:
                        oneSecondsWonder.play();
                        break;
                    case STOPPED:
                        oneSecondsWonder.play();
                        break;
                }                
            });
    
            VBox root = new VBox(btn, label);
    
            Scene scene = new Scene(root, 300, 250);
    
            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-19
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 2018-07-31
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      相关资源
      最近更新 更多