由于某种原因,我的程序找不到图像。我已经尝试了一切,并确保文件路径是准确的。它在我之前的游戏中运行良好,但现在它根本找不到图像。
实体类
package Entities;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Entity
{
public double x, y, width, height, dx, dy;
public BufferedImage image;
public Entity(String s)
{
try
{ //error occurs here
image = ImageIO.read(getClass().getResourceAsStream(s));
}
catch (IOException e)
{
e.printStackTrace();
}
width = image.getWidth();
height = image.getHeight();
}
public void update()
{
x += dx;
y += dy;
}
public void draw(Graphics2D g)
{
g.drawImage(image, (int)x, (int)y, null);
}
}
游戏面板类
package Main;
//import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import Entities.Entity;
@SuppressWarnings("serial")
public class GamePanel extends JPanel implements Runnable, KeyListener
{
public static final int WIDTH = 320;
public static final int HEIGHT = 240;
public static final int SCALE = 2;
//game thread
private Thread thread;
private boolean running;
private int fps = 60;
private long targetTime = 1000/fps;
//image
private BufferedImage image;
private Graphics2D g;
//test
public Entity e;
public GamePanel()
{
super();
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setFocusable(true);
requestFocus();
}
public void addNotify()
{
super.addNotify();
if(thread == null)
{
thread = new Thread(this);
addKeyListener(this);
thread.start();
}
}
public void init()
{
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
running = true;
e = new Entity("Resources/Test/test.png");
}
@Override
public void keyPressed(KeyEvent key)
{
//p1.keyPressed(key.getKeyCode());
}
@Override
public void keyReleased(KeyEvent key)
{
//p1.keyReleased(key.getKeyCode());
}
@Override
public void keyTyped(KeyEvent arg0)
{
}
@Override
public void run()
{
init();
long start;
long elapsed;
long wait;
//game loop
while(running)
{
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed/1000000;
if(wait < 0)
{
wait = 5;
}
try
{
Thread.sleep(wait);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private void drawToScreen()
{
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
g2.dispose();
}
private void draw()
{
//e.draw(g);
}
private void update()
{
}
}
这是错误
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at Entities.Entity.<init>(Entity.java:19)
at Main.GamePanel.init(GamePanel.java:67)
at Main.GamePanel.run(GamePanel.java:93)
at java.lang.Thread.run(Unknown Source)