我试过stage.close(),Platform.exit()和System.exit()无济于事;他们都关闭了应用程序,但直接关闭.如果没有按下 Robot 按Alt F4,有没有顺利的方法来做到这一点? (我也可以想象从算法中创建一个函数并在setOnCloseRequest()中调用它,以及我可能需要它的任何地方).
您可以从舞台获取事件处理程序并调用它.
stage.getOnCloseRequest()
.handle(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
但是你想要做的不仅仅是调用你的自定义关闭请求处理函数,而是激活一个关闭请求事件,它将运行你的处理程序和窗口的任何其他关闭事件处理程序(所以,默认情况下它也会关闭窗口).
stage.fireEvent(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
示例应用程序
运行下面的示例(Java 8)以查看两种方法的行为之间的差异:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class CloseMonitor extends Application {
@Override
public void start(Stage stage) {
stage.setOnCloseRequest(
event -> System.out.println("Close Requested")
);
Button handleClose = new Button("Handle Close Request");
handleClose.setOnAction(
event -> stage.getOnCloseRequest()
.handle(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
);
handleClose.setMaxWidth(Double.MAX_VALUE);
Button fireClose = new Button("Fire Close Request");
fireClose.setOnAction(
event -> stage.fireEvent(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
);
fireClose.setMaxWidth(Double.MAX_VALUE);
stage.setScene(
new Scene(
new VBox(
10,
handleClose,
fireClose
)
)
);
stage.show();
stage.sizeToScene();
}
public static void main(String[] args) {
launch(args);
}
}
翻译自:https://stackoverflow.com/questions/24483686/how-to-force-javafx-application-close-request-programmatically