how to load the images in java runnable jar?

大兔子大兔子 提交于 2020-01-13 05:21:09

问题


When I convert my project into runnable jar the same system, the image is loading in the output. But when I tried in another system, the image failed to load? how to give the image URL rather then using c: ?please help on this?

JToolBar toolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);

JButton capturebut = new JButton(new ImageIcon("C:\\sampleprojects\\
       compare\\shankar\\src\\capture.gif"));

capturebut.setToolTipText("Capture");

toolbar.add(capturebut);

回答1:


Use getResourceAsStream

http://download.oracle.com/javase/tutorial/uiswing/components/icon.html

http://www.jugpadova.it/articles/2006/02/05/accessing-a-resource-within-a-jar




回答2:


You need to put the image file into the JAR file, then use the getResource() method of java.lang.Class to get an URL that references the file which is within the JAR file; right now your code is loading the image file directly from your filesystem instead of from in the JAR file.

The string you pass to getResource() depends upon where you put it in the JAR file. If the class doing this is class Foo in package com.acme.bar, you could put capture.gif in the same com\acme\bar\ subdir of the JAR file (in the same directory as the Foo class), and do

JButton capturebut = new JButton(new ImageIcon(Foo.class.getResource("capture.gif")));

This is because calling getResource() on a class with a relative name (not starting with /) will look for the resource under the same directory as where the class file for that class is sitting.

On the other hand, you could make a resources\images sub-directory under the root of the JAR file, and instead of "capture.gif" use "/resources/images/capture.gif". Starting the name with a '/' makes it search starting at the root of the JAR file, instead of relative to where the class file is.



来源:https://stackoverflow.com/questions/7963155/how-to-load-the-images-in-java-runnable-jar

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