Reputation: 376
If there are unsaved changes, I want to prevent my application (class Foo
) from closing after the user clicks the window close control (the 'X' in the window frame). Following tips here and elsewhere, I have Foo
implement EventHandler<WindowEvent>
. The handle()
method queries the controller for unsaved changes and, if it finds any, consumes the event. The structure looks as follows.
public class Foo extends Application implements EventHandler<WindowEvent> {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Foo.fxml"));
Parent root = (Parent) loader.load();
controller = (FooController) loader.getController();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setOnCloseRequest(this); // handle window close requests
stage.show();
}
@Override
public void handle(WindowEvent t) {
if (t.getEventType() == WindowEvent.WINDOW_CLOSE_REQUEST) {
if (controller.isDirty()) {
t.consume();
}
}
}
}
Using print statements and the debugger, I confirmed that the handler fires and the event is consumed. I also confirmed that the Application.stop()
method is never called. Nonetheless, as soon as handle()
exits, the window closes. (The application's thread is still running, though.) For what it's worth, the application is just a stub: the scene is drawn, but none of the menu items or controls function, it creates no additional threads, etc.
What am I missing?
Upvotes: 0
Views: 1722
Reputation: 3165
I just wrote a small test app. Consuming the event does prevent the window from closing. Looking at the code you posted, I have no idea why it doesn't work for you. Could you
a) state the JavaFX-Version you are using (System.out.println(com.sun.javafx.runtime.VersionInfo.getRuntimeVersion());
) and
b) run the code below and tell me whether this works for you?
I'm trying to find out whether it's a bug in JavaFX or some side effect within your application.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Test extends Application {
@Override
public void start(final Stage stage) throws Exception {
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(final WindowEvent windowEvent) {
windowEvent.consume();
}
});
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Upvotes: 2