Double buffered image example in Jpanel

為{幸葍}努か 提交于 2019-12-11 04:58:41

问题


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

回答1:


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 (i.e. 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.




回答2:


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.



来源:https://stackoverflow.com/questions/18310661/double-buffered-image-example-in-jpanel

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