javafx 关闭系统的提示
时间: 2023-10-29 10:05:16 浏览: 51
你可以使用 JavaFX 中的 Dialog 对象来创建一个确认对话框,询问用户是否要关闭系统。以下是一个示例代码:
```java
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ClosePrompt extends Application {
private Stage stage;
@Override
public void start(Stage primaryStage) throws Exception {
stage = primaryStage;
Button closeButton = new Button("Close");
closeButton.setOnAction(event -> {
Dialog<Boolean> dialog = new Dialog<>();
dialog.setTitle("Close Confirmation");
dialog.setHeaderText("Are you sure you want to close the application?");
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
VBox vbox = new VBox(new Label("Any unsaved changes will be lost."));
dialogPane.setContent(vbox);
dialog.setResultConverter(buttonType -> buttonType == ButtonType.YES);
dialog.showAndWait().ifPresent(result -> {
if (result) {
Platform.exit();
}
});
});
VBox vbox = new VBox(closeButton);
Scene scene = new Scene(vbox, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这段代码创建了一个按钮,当用户点击该按钮时,会弹出一个确认对话框,询问用户是否要关闭系统。如果用户点击“是”,则程序会退出。否则,程序继续运行。