简体   繁体   English

Jpanel中的双缓冲图像示例

[英]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. bufferimage的创建移出paintComponent()方法。 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. 当您完成从bufferImage检索到的Graphics (即您的情况下的dbg变量)时,应该在其上调用dispose()

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 . 最后,如果确保您的组件和包含该组件的组件的属性doubleBufferred设置为true ,那么您也许可以摆脱第二张图片。

All the paintComponent() method should do is draw the image. paintComponent()方法应该做的就是绘制图像。

The "if game is running" code does not belong in the paintComponent() method. “如果游戏正在运行”代码不属于paintComponent()方法。 The idea is to have a Timer or something that changes the state of your game and does the custom drawing on your image. 这个想法是要有一个Timer或可以改变游戏状态并在图像上进行自定义绘制的东西。 Then when Swing invokes the paintComponent() method you simple paint the image in its current state. 然后,当Swing调用paintComponent()方法时,您可以简单地以当前状态绘制图像。

Take a look at the DrawOnImage example from Custom Painting Approaches . 看一下“自定义绘画方法”中的DrawOnImage示例。 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. 在游戏中,可能会发现每次修改图像时也会对其进行绘制,但是代码不应成为paintComponent()方法的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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