JavaFX Running a large amount of countdown timers at once?

前端 未结 4 1120
面向向阳花
面向向阳花 2021-01-28 10:04

So I can see a couple different ways to do what I need and I\'ve done a bunch of google/stack overflow searching but can\'t find really what I\'m looking for. I need to run mult

4条回答
  •  盖世英雄少女心
    2021-01-28 10:39

    What you are looking for is RxJava and its bridge to JavaFx which is RxJavaFx. Import dependency:

    
        io.reactivex.rxjava2
        rxjavafx
        2.2.2
    
    

    and run

    import java.util.concurrent.TimeUnit;
    
    import io.reactivex.Observable;
    import io.reactivex.rxjavafx.observables.JavaFxObservable;
    import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
    import io.reactivex.schedulers.Schedulers;
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.ToggleButton;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class TimersApp extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage stage) throws Exception {
    
            VBox vBox = new VBox();
            for (int i = 0; i < 4; i++) {
                ToggleButton button = new ToggleButton("Start");
                Label label = new Label("0");
                HBox hBox = new HBox(button, label, new Label("seconds"));
                vBox.getChildren().add(hBox);
    
                JavaFxObservable.valuesOf(button.selectedProperty())
                .switchMap(selected -> {
                    if (selected) {
                        button.setText("Stop");
                        return Observable.interval(1, TimeUnit.SECONDS, Schedulers.computation()).map(next -> ++next);
                    } else {
                        button.setText("Start");
                        return Observable.empty();
                    }
                })
                .map(String::valueOf)
                .observeOn(JavaFxScheduler.platform())
                .subscribe(label::setText);
            }
    
            stage.setScene(new Scene(vBox));
            stage.show();
        }
    }
    

    Let me know if you are intrested in this solution. I will provide you some materials to learn.

提交回复
热议问题