问题
I am having trouble getting my ImagePanel to display when I pack it was a jar. When I run the project from Eclipse it displays just fine. here is the line that creates the ImagePanel:
ImagePanel panel = new ImagePanel(this.getClass().getClassLoader()
.getResource("edu/luc/tictactoe/gui/resources/images/UIMM.png"));
frame.setContentPane(panel);
and here is the ImagePanel class:
@SuppressWarnings("serial")
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel(URL url) {
super(true);
this.setToolTipText(url.getPath());
try {
img = ImageIO.read(new File(url.getPath()));
this.setPreferredSize(new Dimension(
img.getWidth(), img.getHeight()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
Any suggestions?
回答1:
img = ImageIO.read(new File(url.getPath())); // REMOVE!
Try this instead..
img = ImageIO.read(url);
BTW - When things go wrong it would pay not to stumble blindly through what is happening. Better to use a debugger and examine the actual values passed, or at least use System.out.pritln()
as a sanity check. E.G.
import java.net.URL;
class URLTest {
public static void main(String[] args) throws Exception {
URL url = new URL("jar:file:/C:/baz.jar!/COM/foo/Quux.class");
System.out.println(url);
System.out.println(url.getPath());
}
}
Output
jar:file:/C:/baz.jar!/COM/foo/Quux.class
file:/C:/baz.jar!/COM/foo/Quux.class
Now tell me. Does the path even look like a file name/path?
When in doubt. Print out.
回答2:
you need to make it into a jar, within the folder that you've made it in make a folder called "edu" in that a folder called "tictactoe" in that "gui" in that "resources" in that "images" and finaly in that, make a picture called "UIMM.png"
in other words, make the same folder structure with in the folder the jar in in.
I had the same problem as well p.s I think you are using a mac, if you are, bundle it with Jar Bundler app, it's the best bundler for a mac
来源:https://stackoverflow.com/questions/8385588/using-an-image-panel-with-a-jar