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);
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
:
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.