当我试图弄清楚如何使用缓冲策略时,总体上只是改进我编写代码和清理东西的方式。当我运行以下代码时,当我“createBufferStrategy(3)”时出现错误
package Game1Test;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.swing.*;
public class Base extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
private boolean running = false;
int ticks = 0;
public Base(JFrame f) {
setSize(f.getWidth(),f.getHeight());
start();
}
public void start(){
running = true;
new Thread(this).start();
}
public void stop(){
}
public void run(){
while(running){
ticks++;
System.out.println(ticks);
render();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void render(){
BufferStrategy bs = getBufferStrategy();
Graphics g;
if(bs == null){
createBufferStrategy(3);
requestFocus();
return;
}
bs.show();
}
}
然后添加基础:
package Game1Test;
import java.awt.*;
import javax.swing.JFrame;
public class Screen extends JFrame{
public final int GAME_WIDTH = 400;
public final int GAME_HEIGHT = 400;
public Dimension gameDim = new Dimension(GAME_WIDTH,GAME_HEIGHT);
final String gameName = "Test";
public Screen(){
setSize(gameDim);
setTitle(gameName);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(new GridLayout());
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args){
Screen s = new Screen();
s.add(new Base(s));
}
}
我收到以下错误:
Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.<init>(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.<init>(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at Game1Test.Base.render(Base.java:46)
at Game1Test.Base.run(Base.java:33)
at java.lang.Thread.run(Unknown Source)
有人可以告诉我为什么会这样吗?也许可以解决这个问题?
谢谢