自动关闭 Java FX 应用可能处于 window 的睡眠模式

Auto Close Java FX App likely Sleep mode of window

我是 Java FX 的新手。如果用户在一段时间内不活动,我希望关闭我的 JavaFX 应用程序。换句话说,如果在持续时间内没有任何鼠标事件或按键事件,应用程序将自动关闭这可能是 Window

的睡眠模式

我确实尝试了 中的代码。但是我的程序不起作用

我从 https://www.callicoder.com/javafx-fxml-form-gui-tutorial/ 得到了一个例子。 我在 RegistrationFormApplication Class

上编辑
public class RegistrationFormApplication extends Application {
 private Timeline timer;
 Parent root ;
@Override
public void start(Stage primaryStage) throws Exception{
     timer = new Timeline(new KeyFrame(Duration.seconds(3600), new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            // TODO Auto-generated method stub
            root = null;
            try {
                root = FXMLLoader.load(getClass().getResource("/example/registration_form.fxml"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                primaryStage.setTitle("Registration Form FXML Application");
                primaryStage.setScene(new Scene(root, 800, 500));
                primaryStage.show();        

        }
     }));

     timer.setCycleCount(Timeline.INDEFINITE);
     timer.play();

     root.addEventFilter(MouseEvent.ANY, new EventHandler<Event>() {
         @Override
         public void handle(Event event) {
             timer.playFromStart();
         }
     });

感谢帮助

获取RxJavaFx和运行代码。在 4 秒不活动(没有任何事件)后,它将关闭应用程序。

    import java.util.concurrent.TimeUnit;

    import io.reactivex.Observable;
    import io.reactivex.schedulers.Schedulers;
    import io.reactivex.subjects.PublishSubject;
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.input.InputEvent;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;

    public class CloseAfterApp extends Application {


        public static void main(String[] args) {
            launch(args);
        }

        @Override
        public void start(Stage stage) throws Exception {
            Scene scene = new Scene(new TextField());

            PublishSubject<InputEvent> sceneEventPublishable = PublishSubject.create();
            PublishSubject<WindowEvent> windowEventPublishable = PublishSubject.create();

            scene.addEventFilter(InputEvent.ANY, sceneEventPublishable::onNext);
            stage.addEventFilter(WindowEvent.ANY, windowEventPublishable::onNext);

            Observable.merge(sceneEventPublishable, windowEventPublishable)
            .switchMap(event -> Observable.just(event).delay(4, TimeUnit.SECONDS, Schedulers.single()))
            .subscribe(event -> Platform.exit());

            stage.setScene(scene);
            stage.show();
        }
    }