我正在尝试学习编写我的第一个游戏,我想正确理解我所做的每一步。稍后我将面临双重缓冲和其他事情。我只是想在游戏循环中加载图像。我有两节课。第一个它只是一个调用 start 方法的 jframe。我想知道这里是否有一些丑陋的代码(我想是的)。那么,为什么我的图像不显示?
public class myPanel extends JPanel implements Runnable{
//FIELDS
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private BufferedImage bg;
private BufferedImage charac;
private boolean running;
private Thread t1;
private int startposX = WIDTH / 2;
private int startposY = HEIGHT / 2;
private int cordX = startposX;
private int cordY = startposY;
int speed = 50;
//METHODS
public synchronized void start (){
running = true;
t1 = new Thread (this);
t1.start();
}
public synchronized void stop (){
running = false;
try {
t1.join();
System.out.println("The game stopped");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//INIT
public myPanel(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
addKeyListener(this);
}
//MAIN RUN METHOD
public void run(){
while (running){
load();
System.out.println("The game runs");
repaint();
}
}
//PAINT WITH GRAPHICS METHOD
public void paint (Graphics g){
super.paint(g);
g.drawImage(bg, 0, 0, this);
g.drawImage(charac, 110, 280, this);
}
//LOAD IMAGES IN MEMORY
public void load (){
try {
String path1 = "res/bg.png";
bg = ImageIO.read(new File (path1));
String path2 = "res/charac.png";
charac = ImageIO.read(new File (path2));
} catch (IOException e) {
e.printStackTrace();
}
}