运行java -jar时未绘制Java映像 [英] Java Images not drawn when running java -jar

查看:48
本文介绍了运行java -jar时未绘制Java映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以前从未遇到过的问题,无法在网络上找到解决方案.我有一个小的Programm,它使用一些图像来打印菜单.

I have a problem i have never had before and couldnt find a solution on the web. I have a small Programm which uses some images to print a menu.

这是我用来打印图像的类:

This is the Class i use to print the Images:

public class ViewImage extends JPanel {
    private static final long serialVersionUID = 1L;
    protected Image image = null;

    public ViewImage(int x, int y, String path) {
        this(x, y, new ImageIcon(path).getImage());
    }

    public ViewImage(int x, int y, Image image) {
        this.image = image;
        this.setBounds(x, y, image.getWidth(null), image.getHeight(null));
    }

    public void paintComponent(Graphics g) {
        int x = ((this.getWidth() - image.getWidth(null)) / 2);
        int y = ((this.getHeight() - image.getHeight(null)) / 2);

        g.drawImage(image, x, y, null);
    }

    public void setImage(String path) {
        this.image = new ImageIcon(path).getImage();
    }
 }

我的图片"都是类路径的一部分,我称之为:

My Images are all part of the classpath an i call them with:

this.getClass().getClassLoader().getResource("MyImage.png").getPath()

工作正常,直到我将程序打包到jar文件中并运行从控制台使用它:

Works fine until i package my programm into a jar file and run it from console with:

java -jar MyJar.jar

我的程序启动正常,但是没有图像打印.没有例外,没有错误,什么都没有.

My programm starts well but no image are printed. No Exceptions, no Errors, nothing.

什么会导致这种行为?

推荐答案

在确保资源正确加载之前(例如,使用System.out())!

Before all be sure your resource is correctly loaded (for example with a System.out())!

代替使用 ImageIcon(String location)使用 ImageIcon(URL location)构造函数,因为您的图像不在hdd上,而是作为URL压缩在类路径中(某些东西)例如MyJar.jar!/path/to/image.png);您必须将图片加载方式修改为

Instead to use ImageIcon(String location) use ImageIcon(URL location) constructor because your image is not on hdd, but live compressed as URL in your classpath (something like MyJar.jar!/path/to/image.png"); you have to modify your image loading as

this.getClass().getClassLoader().getResource("MyImage.png");

这篇关于运行java -jar时未绘制Java映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆