如何更改"警报"对话框的图标?

she*_*n96 3 java user-interface alert javafx

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

这就是我想要改变的:

截图

我想改变Icon.这意味着我想将蓝色图标更改为其他内容.不要改变alret类型

Sai*_*dem 6

除了@Zephyr已经提到的内容之外,如果要在屏幕截图中指向的位置设置自己的自定义图标/图形,请使用类的setGraphic()方法javafx.scene.control.Dialog.

在下面的代码中,虽然alertType是INFORMATION,但它将使用提供的图形节点覆盖预定义的图标.

Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("My Title");
alert.setContentText("My Content text");
alert.setHeaderText("My Header");
alert.setGraphic(new Button("My Graphic"));
alert.show();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Zep*_*hyr 6

你有几个选择.

首先,AlertAlertType在创建警报时接受参数.有5个内置选项可供选择,每个选项都有自己的图标:

INFORMATION,CONFIRMATION,WARNING,ERROR,和NONE(提供无图标在所有).

您可以在创建Alert传递AlertType给构造函数时选择其中一个图标:

Alert alert = new Alert(AlertType.ERROR);

错误截图


但是,如果你要提供你自己的图标图像,您可以通过访问这样做dialogPaneAlert,并设置graphic属性:

alert.getDialogPane().setGraphic(new ImageView("your_icon.png"));
Run Code Online (Sandbox Code Playgroud)

下面是一个简单的应用程序,演示如何使用自定义图标图像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();
    }
}
Run Code Online (Sandbox Code Playgroud)

由此产生Alert:

自定义图标警报


注意:正如Sai Dandem的同样有效的答案所示,您不仅限于使用ImageView图形.该setGraphic()方法接受任何Node对象,所以你可以很容易地通过一个Button,Hyperlink或其他UI组件.