BufferStrategy IllegalStateException

I’ve moved over to use BufferStrategy from BufferedImage for my first attempt at a game (I’m using Java2D as a learning experience) and the performance boost is pretty noticeable. I’m constructing the game as an applet for the time being and it’s all working fine, but when running it from Netbeans/AppletViewer I get an ugly IllegalStateException showing up in the console when I close down the applet. Presumably that’s because I’m killing it mid-flow.

Is there any particular way I should be handling this? I could of course put the BufferStrategy code in a try block and handle the exception that way, but I just wanted to check if that was the right thing to do and/or if there is a better way of doing it?

Well, how are you killing it?

Well I presume it’s the act of closing down the applet, as in closing the window. It’s only an (un?)educated guess as everything is fine when it’s running!

I’m just checking if there is anything else I should be doing. Below is my game loop code, which is pretty similar to tutorials and other posts on this board. I’ve never seen any examples of putting the drawing code in a try block and was wondering if there was a reason for it and if the IllegalStateException is common when exiting. The exception might not even be an issue since I’m closing it down anyway, but I’ve only been playing with BufferStrategy for the last week so I’m very green!


        while(t == gameloop) {
            threadDelay = GAME_FRAME_DELAY - (System.currentTimeMillis() - lastloop);
            try {
                Thread.sleep(threadDelay);
            } catch (InterruptedException e) {
                //do nothing
            }

            //update game logic
            gameUpdate();

                do{
                    do{
                        Graphics2D g = (Graphics2D)strategy.getDrawGraphics();

                        render(g);

                        g.dispose();
                    }while(strategy.contentsRestored());

                    strategy.show();
                    Toolkit.getDefaultToolkit().sync();
                } while(strategy.contentsLost());
            
            lastloop = System.currentTimeMillis();
        }
    }

I’ve never gotten an exception from closing down an applet using BufferStrategy before.

However, this image should give me all the information I need:

If I ever get an office, this is what I’d put up.

It’s my most favorite picture in the world :slight_smile: