首页 > 解决方案 > 如何更改警报对话框的图标?

问题描述

我想更改以下警报消息的默认图标。我该怎么做?

这就是我想要改变的:

截屏

我想更改图标。这意味着我想把那个蓝色图标改成别的东西。不改变警报类型

标签: javauser-interfacejavafxalert

解决方案


你有几个选择。

首先,该类在创建警报时Alert接受一个参数。AlertType有 5 个内置选项可供选择,每个选项都有自己的图标:

INFORMATION, CONFIRMATION, WARNING, ERROR, and NONE(根本不提供图标)。

您可以在创建时Alert通过将 传递AlertType给构造函数来选择这些图标之一:

Alert alert = new Alert(AlertType.ERROR);

错误截图


但是,如果您想提供自己的图标图像,您可以通过访问并设置属性来dialogPane实现:Alertgraphic

alert.getDialogPane().setGraphic(new ImageView("your_icon.png"));

下面是一个简单的应用程序,演示了如何使用自定义图标图像Alert

import javafx.application.Application;
import javafx.scene.control.Alert;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Build the Alert
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Alert Test");
        alert.setHeaderText("This uses a custom icon!");

        // Create the ImageView we want to use for the icon
        ImageView icon = new ImageView("your_icon.png");

        // The standard Alert icon size is 48x48, so let's resize our icon to match
        icon.setFitHeight(48);
        icon.setFitWidth(48);

        // Set our new ImageView as the alert's icon
        alert.getDialogPane().setGraphic(icon);
        alert.show();
    }
}

结果Alert

自定义图标警报


注意:正如 Sai Dandem 的同样有效的答案所示,您不限于使用ImageView图形。该setGraphic()方法接受任何Node对象,因此您可以轻松地传递ButtonHyperlink或其他 UI 组件。


推荐阅读