如果我只是创建一个从 扩展的空类javafx.scene.control.Dialog<R>
,当我按下右上角的“x”按钮时它不会关闭。
我如何实现这种行为?API 似乎告诉我,我需要实现一个关闭按钮。但就我而言,我不想要关闭按钮,我只想使用 x 按钮或按 ESC 关闭窗口。这可能吗?
如果我只是创建一个从 扩展的空类javafx.scene.control.Dialog<R>
,当我按下右上角的“x”按钮时它不会关闭。
我如何实现这种行为?API 似乎告诉我,我需要实现一个关闭按钮。但就我而言,我不想要关闭按钮,我只想使用 x 按钮或按 ESC 关闭窗口。这可能吗?
要解决此问题,您可以向对话框添加一个隐藏的关闭按钮。
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class DialogClosure extends Application{
@Override
public void start(Stage stage) throws Exception {
Button openDialog = new Button("Open Dialog");
openDialog.setOnAction(event -> {
Dialog dialog = new Dialog();
dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
Node closeButton = dialog.getDialogPane().lookupButton(ButtonType.CLOSE);
closeButton.managedProperty().bind(closeButton.visibleProperty());
closeButton.setVisible(false);
dialog.showAndWait();
});
stage.setScene(new Scene(openDialog));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
然后,该对话框既满足您能够通过本机窗口系统的窗口关闭图标关闭的要求,也满足 JavaFX Dialog 在对话框中包含关闭按钮以使关闭图标起作用的要求。
或者,您可以使用带有showAndWait的 Stage而不是Dialog。没有任何包含按钮的舞台可以使用窗口系统的关闭窗口图标关闭。
引用Api Docs:
JavaFX 对话框只能在两种情况下“异常”关闭(如上定义):
当对话框只有一个按钮时,或
当对话框有多个按钮时,只要其中一个满足以下要求之一即可:
- 该按钮有一个 ButtonType,其 ButtonData 的类型为 ButtonData.CANCEL_CLOSE。
- 该按钮有一个 ButtonType,其 ButtonData 在调用 ButtonData.isCancelButton() 时返回 true。
...
所以要么添加至少一个按钮或多个按钮,其中一个是 type ButtonData.CANCEL_CLOSE
,例如:
Dialog<ButtonType> dialog = new Dialog<>();
dialog.getDialogPane().getButtonTypes().add(new ButtonType("Got it!", ButtonData.CANCEL_CLOSE));
dialog.setContentText("test");
dialog.showAndWait();
编辑:
此行为在 中实现javafx.scene.control.FXDialog.requestPermissionToClose(Dialog<?>)
,但实际FXDialog
显示的是HeavyweightDialog
它不是公共 API,因此不是真正的扩展点。
在我中,Dialog<ButtonType>
我使用的是@vbargl 所说的:
Window window = alert.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(event -> window.hide());
它关闭了对话框,但它给我带来了一个没有价值的错误。
为了避免它,我也在检查result.get()
和那个result.isPresent()
。
我已经通过以下代码的警报遇到了这种情况。
Alert alert = new Alert(Alert.AlertType.NONE);
alert.setTitle("Export Successful");
alert.setContentText("All the posts have been exported to Posts.txt file
successfully");
alert.show();
唯一的解决方法是创建一个带有按钮的警报或对话框,如下所示。
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Export Successful");
alert.setContentText("All the posts have been exported to Posts.txt file
successfully");
alert.showAndWait();
@eckig 或 @jewelsea 的解决方法工作得很好。但我会使用这样的东西:
// Somewhere in code Dialog<?> dialog = new Dialog<>(); Window window = dialog.getDialogPane().getScene().getWindow(); window.setOnCloseRequest(event -> window.hide());
我不知道这种用途的任何限制,但它对我有用。我建议在对话框初始化后立即初始化窗口,就像上面一样。