#How to control windows close event in javafx?
1 messages · Page 1 of 1 (latest)
<@&987246487241105418> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
Yes, in JavaFX, you can control the window close event by using the setOnCloseRequest method of the Stage class. Here's an example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Window Close Event Example");
// Create a VBox layout
VBox root = new VBox();
Scene scene = new Scene(root, 300, 200);
// Set the close request event handler
primaryStage.setOnCloseRequest(event -> {
// Display a confirmation dialog
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirmation");
alert.setHeaderText("Are you sure you want to close the window?");
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> {
// Close the application
primaryStage.close();
});
// Consume the event to prevent the window from closing automatically
event.consume();
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
In this example, we set an event handler for the setOnCloseRequest method of the primaryStage. Inside this event handler, we display a confirmation dialog asking the user if they want to close the window. If they click "OK", we call primaryStage.close() to close the application. Additionally, we consume the event using event.consume() to prevent the window from closing automatically.
You can customize this code according to your specific requirements.
do u want to trigger code exectution or just a visual or ?
if its code, it should be stage.setOnCloseRequest( ...
thank u, was to trigger code execution