Do you want to change the stage icon in your JavaFX application like in the picture above? Well, before we dive into it. We will discuss a bit about the Image class and the method we’re using in changing the stage or window icon in your JavaFX application.
The Image class is used for loading images from a specified URL. The Image class in JavaFX supports image formats below:
-
Bitmap (BMP)
-
Graphical Interchange Format (GIF)
-
Joint Photographic Experts Group (JPEG)
-
Portable Graphics Format (PNG)
How to change the stage icon in JavaFX
To change the stage icon in JavaFX. You need to specify the image file using the Image class. To do this, you need to define an Image constructor to load the image from a specified location. By the way, you need to store your image file in the source packages in your JavaFX project. To make the image constructor kindly see the sample constructor below.
Image icon = new Image(getClass().getResourceAsStream("icon.png"));
That’s how you load an image using the Image class. To set the image in your application window or in the JavaFX stage you will need to use the getIcons() method and the add() method. Kindly see the sample code below to learn more how to change the stage icon in JavaFX.
stage.getIcons().add(icon);
Example code
In this example code, you will see the full code in showing the application window and change the stage icon in JavaFX application.
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * * @author KENSOFT */ public class Responsive extends Application { @Override public void start(Stage stage) throws Exception { BorderPane root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); Scene scene = new Scene(root); stage.setTitle("Kensoft PH"); stage.setScene(scene); stage.setMinHeight(400); stage.setMinWidth(600); Image icon = new Image(getClass().getResourceAsStream("icon.png")); stage.getIcons().add(icon); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
Output:
Pay attention to the icon in the application window and in the application icon at the taskbar.