How do I change the icon of an Alert dialog?

shehan96 :

I want to change following default icon of a alert message. How can I do it?

This is what I want to change:

Screenshot

I want to change the Icon. It means I want to change that blue icon to something else. Not to change alret type

Zephyr :

You have a couple of options.

First of all, the Alert class accepts an AlertType parameter when creating the alert. There are 5 built-in options to choose from, each with it's own icon:

INFORMATION, CONFIRMATION, WARNING, ERROR, and NONE (which provides no icon at all).

You can select one of these icons when creating the Alert by passing the AlertType to the constructor:

Alert alert = new Alert(AlertType.ERROR);

ERROR screenshot


If, however, you want to provide your own icon image, you can do so by accessing the dialogPane of the Alert and setting the graphic property:

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

Below is a simple application that demonstrates how to use a custom icon image for the 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();
    }
}

And the resulting Alert:

Custom Icon Alert


Note: As Sai Dandem's equally-valid answer illustrates, you are not restricted to using an ImageView for the graphic. The setGraphic() method accepts any Node object, so you could just as easily pass a Button, Hyperlink, or other UI component.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85199&siteId=1