How to set dock icon of Java application

This solution is only available from JDK 9.

In other to set the JDK version on NetBeans, right click on Project > “Properties” >> “Sources” > “Source/Binary format”; and “Libraries” > “Java Platform”.

package main;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Image;
import java.awt.Taskbar;
import java.awt.Toolkit;

 * author: flohall
 * date: 2019-07-07
public final class Main {

    public static void main (String[] args){

        final JFrame jFrame = new JFrame();

        //loading an image from a file
        final Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        final URL imageResource = Main.class.getClassLoader().getResource("resources/images/icon.gif");
        final Image image = defaultToolkit.getImage(imageResource);

        //this is new since JDK 9
        final Taskbar taskbar = Taskbar.getTaskbar();

        try {
            //set icon for mac os (and other systems which do support this method)
        } catch (final UnsupportedOperationException e) {
            System.out.println("The os does not support: 'taskbar.setIconImage'");
        } catch (final SecurityException e) {
            System.out.println("There was a security exception for: 'taskbar.setIconImage'");

        //set icon for windows os (and other systems which do support this method)

        //adding something to the window so it does show up
        jFrame.getContentPane().add(new JLabel("Hello World"));

        //some default JFrame things

External References

Leave a Reply

Your email address will not be published. Required fields are marked *