As the title says, my question is, how can I prevent/cancel closing of primary stage in JavaFX 2.2? I have done some research on Google, and the following two links seemed t
I think you got the onCloseRequest()
concept wrong. If you consume the event you cancel the closing! So it works the other way round, if canExit()
returns false you consume the event
I have used following code in my application and it works perfectly,
Platform.setImplicitExit(false);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
event.consume();
}
});
I think this is a bug with JavaFX for Linux. I ran in to the same problem on Javafx 2.2.21-b11. Depending on the context the GTK errors may or may not be present, but either way consuming the close request event didn't prevent the window from closing (yet the process continues to run). The same app on Windows behaved as I would expect. So at best we have a difference in behavior across platforms.
I filed a bug report you can upvote if you'd like: https://javafx-jira.kenai.com/browse/RT-33295
Here's the source of my test app
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Boom extends Application {
@Override
public void start(final Stage primary) {
System.out.println(com.sun.javafx.runtime.VersionInfo.getRuntimeVersion());
primary.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
e.consume();
}
});
primary.show();
}
public static void main(String[] args) {
launch(args);
}
}
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
AlertHelper addMore = new AlertHelper("Exit application? Any unsaved data will be lost", "Attention", "Confirmation Required");
boolean actionNeeded = addMore.populatePopup();
if (actionNeeded) {
System.exit(0);
} else {
event.consume();
}
}
});