ゲーム キャンバスを作成していますが、何らかの理由で正しく動作しません。InvalidStateException が発生しましたが、何が原因なのかわかりません。誰でも光を当てることができますか?
私のメインエントリーポイントは…
public class GameTemplate {
public static void main(String[] args) {
new GameFrame();
}
}
私のJFrameサブクラス...
import java.awt.Dimension;
import javax.swing.JFrame;
public class GameFrame extends JFrame {
public static final short WIDTH = 1024;
public static final short HEIGHT = WIDTH / 16 * 9;
public static final Dimension size = new Dimension(WIDTH, HEIGHT);
public GameFrame() {
super("Game Frame");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(size);
this.setLocationRelativeTo(null);
this.setResizable(false);
GameCanvas canvas = new GameCanvas(size);
this.add(canvas);
canvas.start();
this.setVisible(true);
}
}
私のCanvasサブクラス...
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferStrategy;
public class GameCanvas extends Canvas implements Runnable {
private boolean isRunning = false;
private Thread thread = null;
private BufferStrategy bs = null;
private Graphics g;
private Graphics2D g2d;
public GameCanvas(Dimension size) {
this.setSize(size);
this.setVisible(true);
}
public synchronized void start() {
isRunning = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (isRunning) {
update();
draw();
render();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update() {
}
private void render() {
bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
bs.show();
}
private void draw() {
if (bs != null) {
g = bs.getDrawGraphics();
g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g.drawRect(0, 0, WIDTH, HEIGHT);
}
}
}
エラー...
Exception in thread "Thread-1" 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 GameCanvas.render(GameCanvas.java:63)
at GameCanvas.run(GameCanvas.java:47)
at java.lang.Thread.run(Unknown Source)