setIconImage only works in eclipse, doesnt work when exported as runnable jar file

廉价感情. 提交于 2019-12-04 06:40:05

问题


I have searched for a while now for a fix to this. I have a project folder in my workspace (that folder is basically my root), and in it there is a file called icon.gif. In my program, I have the following:

package com.mgflow58.Main;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class Game {

    public static void main(String[] args) {
        JFrame window = new JFrame("Guppy's Adventure");
        window.add(new GamePanel());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);
        window.setIconImage(new ImageIcon("icon.gif").getImage());
    }

}

The icon works fine in eclipse when I run it, but the exported jar file does not display the icon as it does in eclipse. Any idea why? I'm going crazy trying to figure this out.


回答1:


The jar file contains all the image files needed in their proper folders.

There is the problem...ImageIcon(String) is looking for the named file on the disk as described by the JavaDocs...

public ImageIcon(String filename)

Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:

new ImageIcon("images/myImage.gif")

The description is initialized to the filename string.

Parameters:
filename - a String specifying a filename or path

The resources no longer reside on the disk, but are not embedded within the Jar file, so they can no longer be accessed by using File based methods.

Instead, you will need to use something like Class#getResource, for example...

window.setIconImage(new ImageIcon(Game.class.getResource("icon.gif")).getImage());

Having said this, I would also recommend using ImageIO over ImageIcon for a number of reasons, but mostly, because it will actually throw an exception if the resource can't be loaded for some reason, rather than failing silently...

Take a look at Reading/Loading an Image for more details



来源:https://stackoverflow.com/questions/27306872/seticonimage-only-works-in-eclipse-doesnt-work-when-exported-as-runnable-jar-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!