我正在创建一个游戏,背景和主角不会加载。这是我声明变量的地方:
private BufferedImage background;
private BufferedImage player;
这是我获取图片的地方:
try {
background = ImageIO.read(this.getClass().getResourceAsStream("/res/Background.jpg"));
player = ImageIO.read(this.getClass().getResourceAsStream("/res/Player.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是我的渲染方法:
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(background, 0, 0, this);
g.drawImage(player, 0, 0, this);
g.dispose();
bs.show();
}
这是我的全班:
public class Main extends Canvas implements Runnable, KeyListener {
Thread t;
boolean running = false;
private BufferedImage background;
private BufferedImage player;
public Main() {
setFocusable(true);
requestFocus();
addKeyListener(this);
try {
background = ImageIO.read(this.getClass().getResourceAsStream("/res/Background.jpg"));
player = ImageIO.read(this.getClass().getResourceAsStream("/res/Player.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
while (running) {
tick();
render();
}
stop();
}
synchronized void start() {
if (running) return;
running = true;
Thread t = new Thread();
t.start();
}
synchronized void stop() {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(background, 0, 0, this);
g.drawImage(player, 0, 0, this);
g.dispose();
bs.show();
}
public void tick() {
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
JFrame f = new JFrame("Mission Sahara");
Main m = new Main();
f.add(m);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setUndecorated(true);
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m.start();
}
}
我的代码出了什么问题?
答案 0 :(得分:1)
你正在创造一个空的" Thread
方法中的start
...
Thread t = new Thread();
t.start();
并没有做很多事情。
相反,你可能想做类似的事情......
synchronized void start() {
if (running) {
return;
}
running = true;
Thread t = new Thread(this);
t.start();
}
因为Main
实现了Runnable