我有一些问题。我正在学习编程游戏,我想尝试自己编写一些游戏。但是刚开始时我遇到了麻烦。我有2节课。主类(调用Frame)仅用于创建游戏框架:
public class Frame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
Game game;
public Frame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
game = new Game();
this.add(game.canvas);
this.pack();
this.setResizable(false);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Frame().setVisible(true);;
}
});
}
}
它正确。但是我创建了第二个类(调用Game),它应该提供游戏循环:
public class Game implements Runnable{
public Canvas canvas;
Thread thread;
BufferStrategy bs;
Graphics g;
//Variables for game loop
private int fps, timePerTick;
double now, lastTime;
private double delta;
Game(){
initVariables();
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(300, 300));
}
private void initVariables(){
//create and start thread
thread = new Thread(this);
thread.start();
}
private void tick(){
}
private void render(){
bs = canvas.getBufferStrategy();
if (bs == null){
canvas.createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
g.drawRect(0, 0, 50, 50);
bs.show();
g.dispose();
}
private void initRun(){
delta = 0;
lastTime = System.nanoTime();
fps = 30;
timePerTick = 1000000000/fps;
}
@Override
public void run() {
initRun();
int timer=0;
int ticks=0;
while(true){
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += (now - lastTime);
lastTime = now;
if(delta>=1){
tick();
render();
delta--;
ticks++;
}
if (timer>1000000000){
System.out.println("FPS: "+ticks);
timer = ticks = 0;
}
}
}
}
问题在于变量调用FPS的价值。当我在方法调用initRun()中将FPS设置为10时,一切都正常。 (简单地感谢方法run()程序写了" FPS:60"每秒,并在框架中绘制一个矩形)。 但是当我将FPS设置为(例如)30时,就出现了问题。线程中有异常调用"异常"线程-1" java.lang.IllegalStateException:组件必须具有有效的对等体"在render()方法中,具体地在指令" canvas.createBufferStrategy(3);"。 (image of exception) 我能做什么?哪里有问题?我不会说英语,所以我不理解这个例外,我不知道,我能做什么......请帮助我!感谢。