本文介绍了使用带有Jar的图像面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我打包它是一个罐子时,我无法显示我的ImagePanel。当我从Eclipse运行项目时它显示得很好。这是创建ImagePanel的行:

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);

这里是ImagePanel类:

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);
    }
}

有任何建议吗?

推荐答案

img = ImageIO.read(new File(url.getPath()));  // REMOVE!

试试这个..

img = ImageIO.read(url);






BTW - 当出现问题时,它不会支付盲目地绊倒正在发生的事情。最好使用调试器并检查传递的实际值,或者至少使用 System.out.pritln()作为完整性检查。 E.G。


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.

这篇关于使用带有Jar的图像面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:02