views:

130

answers:

2

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)
+1  A: 

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.

camickr
I tend to prefer manually updating graphics, so having access to an actual BufferStrategy object makes this pretty straightforward - draw a load of items to the graphics, then simply call strategy.show() once I'm done. Do correct me if this is a horrible way to do things!I will certainly read up a little more on Concurrency.
Will Hamilton
I thought my suggestion showed my opinion of using a BufferedStrategy which I believe may have been helpfull when using AWT but as I mentioned Swing is different. The tuturial also has a section on "Custom Painting" you should look at
camickr
+1  A: 

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();
    }
}
finnw