BufferStrategy Illegal State Exception

2019-07-17 01:29发布

问题:

After a few hours of trying to work this out I am stumped. I am somewhat new to Java and could use some help.

The Stack Trace:

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.mime.crystalnova.Display.render(Display.java:148)
at com.mime.crystalnova.Display.run(Display.java:112)
at java.lang.Thread.run(Unknown Source)

The error appears to be with this line of code here:

BufferStrategy bs = getBufferStrategy();
if (bs == null) {
    createBufferStrategy(3);
    return;
}

The odd thing is that it gives me this error while debugging and then continues to run flawlessly. It works fine when launched via runnable jar file as well.

回答1:

It's probably got to do with the component not being visible yet at the time you call createBufferStrategy() (it's been a while). Try calling it at a later time.

The fact that your app continues to run probably means the component defaulted to a non-buffered strategy.