How do you double buffer in java for a game?

后端 未结 4 1017
逝去的感伤
逝去的感伤 2020-11-27 07:35

So in the game I\'m working on, I have a marble follow the mouse, but when it does this the screen flickers.

The background includes two jpegs and 9 rectangles. How

相关标签:
4条回答
  • 2020-11-27 07:49

    Double buffering is conceptually pretty simple, instead of drawing your objects one by one, you draw them on an image and then tell the renderer to draw that entire image. This eliminates the flickering.

    Here's an example of how you might do this (source)

    class DoubleBufferedCanvas extends Canvas {
    
        public void update(Graphics g) {
        Graphics offgc;
        Image offscreen = null;
        Dimension d = size();
    
        // create the offscreen buffer and associated Graphics
        offscreen = createImage(d.width, d.height);
        offgc = offscreen.getGraphics();
        // clear the exposed area
        offgc.setColor(getBackground());
        offgc.fillRect(0, 0, d.width, d.height);
        offgc.setColor(getForeground());
        // do normal redraw
        paint(offgc);
        // transfer offscreen to window
        g.drawImage(offscreen, 0, 0, this);
        }
    }
    

    Nowdays, you don't have to implement this yourself, you can use the BufferStrategy and releated classes. See lakam99's answer for an example of that .

    0 讨论(0)
  • 2020-11-27 07:51

    Another solution is to use a library that will double buffer for you. Since you are using Java2D I am assuming you want to keep everything pretty lightweight and lower level. I think Slick2D does a great job of providing simple, 2d drawing and input functions without getting in your way. It feels like a more elegant version of Java2D, but is written on OpenGL. Once you make a few applications with pure Java, I think moving to Slick2D is a GREAT idea. This is not a direct solution to your issue, but since it has already been solved I thought Id offer some advice that will make your Java game development life easier. Check it out if you get a chance http://slick.cokeandcode.com/

    0 讨论(0)
  • 2020-11-27 07:55

    Swing supports double buffering automatically, so you don't need to code anything.

    Just call setDoubleBuffered(true) on your top-level component (typically a JPanel) and it should all work.

    See: setDoubleBuffered

    0 讨论(0)
  • 2020-11-27 08:06

    I think your problem is not double buffering. You must add super.paint(page); at the first line of your paint method.

    0 讨论(0)
提交回复
热议问题