嗨,对于不同的 javafx 应用程序,我一直在测试警报,并且唯一在按下警报框的“X”按钮时不起作用。
我在下面添加了一个代码,但如果您没有时间运行它,这里有一个 GIF,用于解释我的警报框有什么问题:
https://giant.gfycat.com/GeneralUntimelyBluewhale.webm
我不太确定如何将 gif 上传到实际帖子中,对此我深表歉意。
有没有办法解决这个问题?
谢谢
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Playground extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
VBox root = new VBox(100);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
Button button = new Button("Alert");
button.setOnAction(event -> {
ButtonType goodButton = new ButtonType("Good");
ButtonType badButton = new ButtonType("Bad");
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "", goodButton, badButton);
alert.showAndWait();
if (alert.getResult().equals(goodButton)) {
System.out.println("Good");
} else if (alert.getResult().equals(badButton)) {
System.out.println("Bad");
}
});
// Add the buttons to the layout
root.getChildren().addAll(button);
// Show the Stage
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
最佳答案
根据 Dialog API 中的“对话结束规则”文档中,默认的“X”按钮只有在至少一个按钮是“CANCEL”类型时才能正常工作。因此,将任何一个按钮更改为 ButtonType.CANCEL 应该会在单击“X”时关闭对话框。
如果您对使用内置按钮不感兴趣,那么您必须根据您的要求明确处理对话框的关闭请求。
ButtonType goodButton = new ButtonType("Good");
ButtonType badButton = new ButtonType("Bad");
Alert alert = new Alert(Alert.AlertType.ERROR,"",goodButton,badButton);
Window window = alert.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(e -> alert.hide());
Optional<ButtonType> result = alert.showAndWait();
result.ifPresent(res->{
if (res.equals(goodButton)) {
System.out.println("Good");
} else if (res.equals(badButton)) {
System.out.println("Bad");
}
});
关于javafx - 当按下 "x"按钮时,Javafx 中的警报不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52472046/