所以,今天我决定尝试不使用教程来制作自己的游戏,如果我有问题,请尝试自己解决。但是,这个问题是我不明白的。
这是我的代码:游戏类(应该在其中渲染图像):
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private int width = 350;
private int height = 200;
private int scale = 3;
private Dimension size = new Dimension(width * scale, height * scale);
private Thread thread;
private boolean running = false;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
private Loader loader;
public Game() {
JFrame frame = new JFrame("Game");
frame.setPreferredSize(size);
frame.setMaximumSize(size);
frame.setMinimumSize(size);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(this);
frame.setVisible(true);
loader = new Loader();
}
public static void main(String[] args) {
Game game = new Game();
game.start();
new Images();
}
public void render() {
BufferStrategy bs = super.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(Images.TEST, 10, 10, null);
g.dispose();
bs.show();
}
public synchronized void start() {
if (running)
return;
else
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
if (!running)
return;
else
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getScale() {
return scale;
}
}
加载器类(我加载图像的地方):
public class Loader {
public BufferedImage loadImage(String fileName) {
try {
System.out.println("Trying to load: " + fileName + " ... succeded!");
return ImageIO.read(new File(fileName));
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("Trying to load: " + fileName + " ... failed!");
return null;
}
}
还有我的图像类,其中所有图像都设置为一个文件:
public class Images {
public static Loader loader;
public static final BufferedImage TEST;
static {
Loader loader = new Loader();
TEST = loader.loadImage("res/test.png");
}
}
我想做的只是简单地在屏幕上显示图像,但这种方法似乎不起作用。我不知道我做错了什么。而且,不,我没有放入错误的图像目录。提前致谢!