gpt4 book ai didi

java - 创建新的 Bufferstrategy 时出现非法状态异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:37 26 4
gpt4 key购买 nike

当我试图弄清楚如何使用缓冲策略时,总体上只是改进我编写代码和清理东西的方式。当我运行以下代码时,在“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();
}



}

然后在 Base 中添加:

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)

谁能告诉我为什么会这样?也许是解决这个问题的方法?

谢谢

最佳答案

看看 API ,如果组件不可显示,则会抛出此异常。在这种情况下,即 Canvas.peernull 时。查看 peer 字段会发现

The peer is set when the Component is added to a container that also is a peer

由于您是从组件的构造函数启动更新线程,因此可以在将组件添加到另一个容器之前调用 render,这意味着 peernull,然后将抛出 IllegalStateException

关于java - 创建新的 Bufferstrategy 时出现非法状态异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com