How do you change the Dock Icon of a Java program?

Apple eAWT provides the Application class that allows to change the dock icon of an application.

import com.apple.eawt.Application;
...
Application application = Application.getApplication();
Image image = Toolkit.getDefaultToolkit().getImage("icon.png");
application.setDockIconImage(image);

While I'm not sure how to change it at runtime, you can set at the command line your Dock icon using the -Xdock:icon option, like:

 >java -Xdock:icon=/path/myIcon.png myApp

This article has lots of useful little info about bringing java apps to Mac, and you may be interested looking at the utilities and tools for Mac listed here, as well as deployment options listed here (the last link is especially useful if you want to go down the Java Webstart route).


Solution for Java 9 and later

In JDK 9, internal APIs such as those in the Mac OS X com.apple.eawt package will no longer be accessible.

see: http://openjdk.java.net/jeps/272

package main;

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

/**
 * 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)
            taskbar.setIconImage(image);
        } 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)
        jFrame.setIconImage(image);

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

        //some default JFrame things
        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
        jFrame.pack();
        jFrame.setVisible(true);
    }
}

This code can be used as is. Just change the path of the image.
This new implemented way (in JDK 9+) of setting the icon for mac os dock is better then before because you won't run into any problem when building your application. Also there is no problem to use this code on a windows computer. Reflection which is not recommended since Java 9 is not needed either.