我在整个网站上都看到了这个问题。我已经阅读了几乎所有的回复。我觉得我正在做需要做的事情,但我就是无法让它发挥作用!我正在尝试将一些图像打包到一个 Runnable Jar 中,以便我的程序是独立的。当我在 Eclipse 中运行代码时,它按预期工作。但是当我使用可执行 Jar 时,程序不会启动。它在我创建图像的行上给了我一个 NullPointerException。这些文件位于项目源文件夹中名为 Resources 的文件夹中。这是代码。它是不完整的,因为这只是我一直试图开始工作的一个测试程序。
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class testgui extends JFrame{
private static JLabel label = new JLabel();
private static testgui gui = new testgui();
private static ArrayList<ImageIcon> sprites;
public static void main(String[] args) {
// TODO Auto-generated method stub
sprites = getImages();
BufferedImage backgroundImage;
try {
backgroundImage = ImageIO.read(new testgui().getClass().getClassLoader().getResource("resources/runescapemap.png"));
gui.setContentPane(gui.new ImagePanel(backgroundImage));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gui.setLayout(new GridLayout(1,2));
label.setIcon(sprites.get(0));
gui.add(label);
gui.setSize(1000,900);
gui.setVisible(true);
}
private static ArrayList<ImageIcon> getImages(){
ImageIcon autoTalkerLogo = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/autotalker-logo.png"));
ImageIcon meterNormal = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/meter.png"));
ImageIcon meterSafe = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/meter-safe.png"));
ImageIcon meterNotSafe = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/meter-notsafe.png"));
ArrayList<ImageIcon> sprites = new ArrayList<ImageIcon>();
sprites.add(autoTalkerLogo);
sprites.add(meterNormal);
sprites.add(meterSafe);
sprites.add(meterNotSafe);
return sprites;
}
class ImagePanel extends JComponent {
private Image backgroundImage;
public ImagePanel(Image image) {
this.backgroundImage = image;
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(backgroundImage, 0, 0, null);
}
}
}