Learn how to define a custom icon for a frame in the AWT Toolkit of Java.

How to change a frame's title bar icon (application icon) in Java AWT Toolkit

The customization of your application is essential to create a confidence feeling for your user. One of those tiny details is the usage of an icon, to leave at least the impression that you are really working dedicatedly in the application. In this article we'll show you how you can quickly change the icon of your application with the code in Java AWT Toolkit.

The only thing you will need is an image to use as icon for your application, if you are lacking of imagination or you just want to test quickly, you can download some random icon from this website. Once you have some icon to use, just follow the next logic:

// Create some frame instance
Frame window = new Frame();

// Create an image instance from the image that you want to use as icon for your app
Image icon = Toolkit.getDefaultToolkit().getImage("C:\\some-directory\\icon.png");  

// And set it
window.setIconImage(icon);

You will need an instance of a Frame that allows the customization of the icon, then create an instance of an Image with the default Toolkit of Java AWT from a local path (note that if the file is inside your project resources, you can use a relative path or join it with the current application path). The getImage method of the toolkit returns an image which gets pixel data from the specified file, whose format can be either GIF, JPEG or PNG. Finally call the setIconImage method from the frame and pass as first argument the instantiated image.

Note

The recommended format is the PNG that allows transparency on your icon so it will look better on any screen.

Application context example

The following code represents the mentioned logic during the initialization of a frame within a structured application context:

package sandbox;

import java.awt.*;  

public class Sandbox {
    
    Sandbox(){
        // Create a new frame
        Frame window = new Frame();
        
        // Create an image instance from the image that you want to use as icon for your app.
        Image icon = Toolkit.getDefaultToolkit().getImage("C:\\some-directory\\icon.png");  
        window.setIconImage(icon);
        
        // Set other options of the frame ...
        window.setLayout(null);
        window.setSize(400,400); 
        window.setVisible(true);
    }   
    
    /**
     * Initialize app.
     * 
     * @param args 
     */
    public static void main(String[] args) {
        Sandbox app = new Sandbox();
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors