1

出于某种原因,当我尝试创建三重缓冲区时出现错误,这是我第一次使用 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)
4

1 回答 1

0

基本上,您正在尝试在组件显示(连接到屏幕)之前创建缓冲策略。这是您的线程和 EDT 之间的竞争条件

你可以检查isDisplayed你的run方法并等到它true

您也可以在使框架可见之后开始您的线程...

于 2013-08-28T02:28:01.727 回答