I am new in Java FX. I expect to close my JavaFX application if the user is inactive for a period of time. In other words App is closed automatically if there are no any mouse event or Key event in for duration It's likely Sleep Mode of Window
I did try the code from Auto close JavaFX application due to innactivity. However My Program doesn't work
I get an example from https://www.callicoder.com/javafx-fxml-form-gui-tutorial/ . And I edited on 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();
}
});
Thanks for help
Get RxJavaFx and run the code. After 4 seconds of inactivity (lack of any events) it will close the app.
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();
}
}