【问题标题】:Double buffered image example in JpanelJpanel 中的双缓冲图像示例
【发布时间】:2013-08-21 01:32:59
【问题描述】:

我会知道我的实现对于双缓冲图像是否正确.. 因为我注意到我在屏幕中移动的图像边框会颤抖...这很正常吗??

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

【问题讨论】:

    标签: java swing bufferedimage double-buffering


    【解决方案1】:

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

    “如果游戏正在运行”代码不属于paintComponent() 方法。这个想法是有一个计时器或其他东西来改变你的游戏状态并在你的图像上进行自定义绘图。然后,当 Swing 调用 paintComponent() 方法时,您只需将图像绘制为当前状态。

    看看Custom Painting Approaches 中的DrawOnImage 示例。该代码使用鼠标将矩形添加到图像中。然后,每当重新绘制组件时,都会绘制图像。

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

    【讨论】:

      【解决方案2】:

      bufferimage 的创建移出paintComponent() 方法。您不需要在每次调用该方法时都创建它。无论如何,您正在绘制整个表面。

      当您处理完从bufferImage 检索到的Graphics(即在您的情况下为dbg 变量)时,您应该调用dispose()

      最后,如果您确保您的组件和包含它的组件将属性 doubleBufferred 设置为 true,那么您可能无需第二张图片就可以逃脱。

      【讨论】:

      • 您的最后一段可能是最重要的一段。大多数 Swing 组件默认是双缓冲的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2014-10-10
      • 1970-01-01
      • 2023-04-06
      • 2021-06-05
      相关资源
      最近更新 更多