Jpanel中的双缓冲图像示例 [英] Double buffered image example in Jpanel

查看:235
本文介绍了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);
}

推荐答案

paintComponent()方法应该做的就是绘制图像.

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

如果游戏正在运行"代码不属于paintComponent()方法.这个想法是要有一个Timer或可以改变游戏状态并在图像上进行自定义绘制的东西.然后,当Swing调用paintComponent()方法时,您只需将图像绘制成当前状态即可.

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.

看看自定义绘画方法中的DrawOnImage示例.该代码通过使用鼠标将矩形添加到图像.然后,每当重新绘制组件时,都会绘制图像.

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.

想法是创建/修改图像一次,然后重新绘制图像.在游戏中,可能会发现每次修改图像时都会对其进行绘制,但是代码不应成为paintComponent()方法的一部分.

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.

这篇关于Jpanel中的双缓冲图像示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆