"Buffers have not been created" ... whilst creating buffers
I have (what I thought was) a straightforward BufferStrategy for a JFrame. It is created like so:
// Buffer
container.createBufferStrategy(2);
strategy = container.getBufferStrategy();
However, occassionally I receive the following error (which points to the first line of the preceeding snippet开发者_开发知识库 as the offending item) :
java.lang.IllegalStateException: Buffers have not been created
This error is peculiar as it comes and goes - sometimes it is triggered, sometimes not. I suspect this means it's a threading issue. Does anyone have any pointers as to what might be going on here? I'm a little at a loss, since I'm already trying to do what Java says it wants me to do!
edit: full trace:
Exception in thread "main" java.lang.IllegalStateException: Buffers have not been created
at sun.awt.windows.WComponentPeer.getBackBuffer(WComponentPeer.java:877)
at java.awt.Component$FlipBufferStrategy.getBackBuffer(Component.java:3815)
at java.awt.Component$FlipBufferStrategy.updateInternalBuffers(Component.java:3800)
at java.awt.Component$FlipBufferStrategy.createBuffers(Component.java:3791)
at java.awt.Component$FlipBufferStrategy.<init>(Component.java:3730)
at java.awt.Component$FlipSubRegionBufferStrategy.<init>(Component.java:4253)
at java.awt.Component.createBufferStrategy(Component.java:3612)
at java.awt.Window.createBufferStrategy(Window.java:3015)
at java.awt.Component.createBufferStrategy(Component.java:3536)
at java.awt.Window.createBufferStrategy(Window.java:2990)
The frame needs to be displayable when you call createBufferStrategy
. Also as camickr has pointed out you need to call it from the EDT.
One way to ensure this is to extend JFrame
and override addNotify
:
class MyFrame extends JFrame {
public void addNotify() {
super.addNotify();
// Buffer
createBufferStrategy(2);
strategy = getBufferStrategy();
}
}
Swing components are double buffered by default, so there is no need to play around with a BufferStrategy.
However when you get random errors like that its usually because code is not executed on the EDT. Read the section from the Swing tutorial on Concurrency for more information.
精彩评论