出于某种原因,当我尝试创建一个tripple缓冲区时出现错误,这是我第一次使用BufferStratrgy类,所以我不一定知道我在做什么。
package com.valgriz.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends Canvas implements Runnable {
public static JFrame frame = new JFrame();
public Thread thread = new Thread(this);
private final int SCALE = 4;
public static void main(String[] args) {
frame.add(new Main());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(360, 480);
frame.setTitle("8ddddd");
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public Main() {
thread.start();
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public void run() {
while (true) {
update();
render();
}
}
}
这是我得到的错误:
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 com.valgriz.main.Main.render(Main.java:37)
at com.valgriz.main.Main.run(Main.java:50)
at java.lang.Thread.run(Unknown Source)
答案 0 :(得分:0)
基本上,您正在尝试在显示组件(连接到屏幕)之前创建缓冲策略。这是Thread和EDT之间的竞争条件
您可以查看run
方法中的isDisplayed
并等到true
。
你可以在框架可见之后启动你的线程......