Domanda

I am currently using the following code segment to get the image for the interface.

ImageIcon img = new ImageIcon("./lib/logo.gif");

JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(img);
lblNewLabel.setBounds(28, 65, 140, 100);

However, when i execute clean and build, the image does not appear when i execute the jar file. What seems to be the problem and where should I put the image file? Thanks in advance.

È stato utile?

Soluzione

"However, when i execute clean and build, the image does not appear when i execute the jar file. What seems to be the problem and where should I put the image file?"

This is the reason you don't load from a file. You want to load it as an embedded resources from your class path with a URL

Your image should be in a package somewhere in the src during development. When you build, the IDE with copy that image for you into the class path, and add it to the jar

enter image description here

Then to load from the class path in your code.

Class.getResource(..) return a URL, so you want to do this

ImageIcon icon = new ImageIcon(MyClass.class.getResource("/images/logo.gif"));

Altri suggerimenti

In the code snippet you provided, the path to the image file is considered to be on the file system (the constructor of class ImageIcon takes a file name as an argument). If you want to load a file (or an image) from the jar itself, you need to use ClassLoader.getResourceAsStream(). Check this question.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top