我试图提示用户在退出之前确认他们要关闭程序。如果任务仍在执行,我想确认他们仍然希望退出或给他们机会让任务在退出前完成。我使用了 setOnCloseRequest,但没有用。我使用了 event.consume,它似乎禁用了 [x] 按钮。任何建议表示赞赏。我在这里发现了一个对我不起作用的类似问题 -> JavaFX stage.setOnCloseRequest without function?
Public class Sample extends Application {
@Override
public void start(Stage stage) throws Exception {
stage.setOnCloseRequest(event -> {
NewScanView checkScan = new NewScanView();
boolean isScanning = checkScan.isScanning();
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Close Confirmation");
alert.setHeaderText("Cancel Creation");
alert.setContentText("Are you sure you want to cancel creation?");
if (isWorking == true){
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
stage.close();
}
if(result.get()==ButtonType.CANCEL){
alert.close();
}
}
});
stage.setHeight(600);
stage.setWidth(800);
stage.setTitle("Title");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
最佳答案
此答案基于对 Javafx internal close request 的回答.那个问题和这个问题不一样,但是答案很相似。
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.*;
import javafx.stage.WindowEvent;
import java.util.Optional;
public class CloseConfirm extends Application {
private Stage mainStage;
@Override
public void start(Stage stage) throws Exception {
this.mainStage = stage;
stage.setOnCloseRequest(confirmCloseEventHandler);
Button closeButton = new Button("Close Application");
closeButton.setOnAction(event ->
stage.fireEvent(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
);
StackPane layout = new StackPane(closeButton);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
private EventHandler<WindowEvent> confirmCloseEventHandler = event -> {
Alert closeConfirmation = new Alert(
Alert.AlertType.CONFIRMATION,
"Are you sure you want to exit?"
);
Button exitButton = (Button) closeConfirmation.getDialogPane().lookupButton(
ButtonType.OK
);
exitButton.setText("Exit");
closeConfirmation.setHeaderText("Confirm Exit");
closeConfirmation.initModality(Modality.APPLICATION_MODAL);
closeConfirmation.initOwner(mainStage);
// normally, you would just use the default alert positioning,
// but for this simple sample the main stage is small,
// so explicitly position the alert so that the main window can still be seen.
closeConfirmation.setX(mainStage.getX());
closeConfirmation.setY(mainStage.getY() + mainStage.getHeight());
Optional<ButtonType> closeResponse = closeConfirmation.showAndWait();
if (!ButtonType.OK.equals(closeResponse.get())) {
event.consume();
}
};
public static void main(String[] args) {
launch(args);
}
}
答案确实使用了 event.consume()
,您说您尝试过但对您不起作用(尽管我不确定为什么不能使用此示例代码,因为它对我来说效果很好).
关于java - 当用户尝试使用 JavaFx 中的 setOnCloseRequest 关闭应用程序时的警告框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31540500/