Search code examples
javaswingiconsjframeimageicon

JFrame.setIconImage() not working


public class RType extends JFrame {

private static ImageIcon ICON = new ImageIcon("craft.png");

public RType() {

    add(new Board());
    setIconImage(ICON.getImage());

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 300);
    setLocationRelativeTo(null);
    setTitle("R - Type");
    setResizable(false);
    setVisible(true);
}

public static void main(String[] args) {
    new RType();
}
}

This code still works fine and compiles after I attempt to set an icon image for the JFrame, but there is no difference. I still see the default java-icon. Can someone detect the problem? "craft.png" is 20x20 pixels. It is correctly placed within the ressource folder (no ClassLoader-exceptions and no other compile-time errors).


Solution

  • ImageIcon(String) expects a file reference, if the icon is an embedded resource, you will need to supply a URL

    Something like...

    private static ImageIcon ICON = new ImageIcon(RType.class.getResource("/craft.png"));
    

    Assuming that craft.png is in the default directory and not some sub directory