“Buffers have not been created” … whilst creating buffers

依然范特西╮ 提交于 2019-12-01 17:13:36

问题


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:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3435994/buffers-have-not-been-created-whilst-creating-buffers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!