简体   繁体   中英

Double buffered image example in Jpanel

I would know if my implementation is correct for double buffered image.. because i note that tremble the borders of my image that i move in the screen ... It is normal??

public void paintComponent(Graphics g) {
    Image bufferimage= createImage(180,180);
    Graphics dbg= bufferimage.getGraphics();

    //clean the screen
    dbg.setColor(new Color(100,100,100));
    dbg.fillRect(0,0,getWidth(),getHeight());

    if (game_is_running) {
       // draw various type of object with drawImage
       for(int i=0; list[i]!=null; i++) {
           list[i].draw(dbg);
       }
       target.draw(dbg);
       I.draw(dbg);
    }

    //finally draw the image linked to graphics
    g.drawImage(bufferimage,0,0,this);
}

Move the creation of the bufferimage out of the paintComponent() method. You don't need to create this every time that method is called. You are drawing the whole surface anyway.

When you are done with the Graphics retrieved from bufferImage (ie dbg variable in your case) you are supposed to call dispose() on it.

Finally you might be able to get away without the second image if you ensure that your component and the components that contain it, have the property doubleBufferred set to true .

All the paintComponent() method should do is draw the image.

The "if game is running" code does not belong in the paintComponent() method. The idea is to have a Timer or something that changes the state of your game and does the custom drawing on your image. Then when Swing invokes the paintComponent() method you simple paint the image in its current state.

Take a look at the DrawOnImage example from Custom Painting Approaches . The code adds rectangles to the image by using the mouse. Then whenever the component is repainted the image is painted.

The ideas is to create/modify the image once and then repaint the image. In a game it may turn out that every time you modify the image you also paint it, but the code should not be part of the paintComponent() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM