Java JApplet 图形双缓冲 [英] Java JApplet Graphics Double Buffering

查看:30
本文介绍了Java JApplet 图形双缓冲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写一个非常简单的游戏,当我在浏览器中以小程序的形式玩游戏时,我遇到了非常严重的闪烁问题.也就是说,我的所有被绘制在背景之上的精灵有时会显示在屏幕上,但通常不会显示 - 它们会反复闪烁到屏幕上然后消失.我读过双缓冲可能是解决这个问题的方法,但我无法正确实现它.

I'm writing a pretty simple game in Java, and I'm running into the issue of very serious flickering when I play the game as an applet in a browser. That is, all of my sprites, which are being painted on top of a background, are sometimes shown onscreen, but usually not - they repetitively flash onto the screen and then disappear. I've read that double buffering is probably the solution to this, but I'm having trouble implementing it correctly.

我使用 JApplet 作为 JPanel 的容器.此 JPanel 是在其上绘制精灵和游戏对象的容器 - 即在 JPanel 的paintComonent 方法中.在我的 JApplet 中,我使用了 init、paint 和 update 覆盖方法,如下所示:

I'm using a JApplet as the container for a JPanel. This JPanel is the container onto which the sprites and game objects are painted - that is, in the JPanel's paintComonent method. In my JApplet, I'm using init, paint, and update override methods as follows:

Image offscreen;

Graphics bufferGraphics;

Dimension dim;

public void init(){
    dim = getSize();

    setBackground(Color.BLACK);

    offscreen = createImage(dim.width,dim.height);

    bufferGraphics = offscreen.getGraphics();

}

public void paint(Graphics g){
    bufferGraphics.clearRect(0,0,dim.width,dim.height);
    //here is my question - i"m not sure what I should print to bufferGraphics
    g.drawImage(offscreen, 0, 0, this);
}

public void update(Graphics g){
    paint(g);
}

我遇到的问题是,在注释行中,我不确定如何将当前小程序图像打印到 bufferGraphics.我读了一个 example,其中精灵直接绘制到 JApplet,不使用 JPanel.有鉴于此,我的猜测是我需要在注释行将 JPanel 绘制到 bufferGraphics 上.我在正确的轨道上吗?任何帮助是极大的赞赏;我只是想知道有什么方法可以正确地做到这一点.

The problem I'm running into is that, at the commented line, I'm unsure of what to do to get the current applet image printed to bufferGraphics. I read an example in which the sprite was painted straight to the JApplet, without using a JPanel. In light of that, my guess is that I'd need to paint the JPanel onto bufferGraphics at the commented line. Am I on the right track here? Any help is greatly appreciated; I just would like to know any way to do this properly.

推荐答案

Swing 默认是双缓冲的,不需要做任何特别的事情.

Swing is double buffered by default, there is no need to do anything special.

您的问题可能是绘画代码.您发布的代码用于 AWT 绘画,而不是 Swing 绘画.

Your problem is probably the painting code. The code you posted is used for AWT painting, NOT Swing painting.

自定义绘制是通过覆盖 JPanel 或 JComponent 的paintComponent() 方法来完成的.我建议您首先阅读 Custom Painting 上的 Swing 教程一个工作示例.

Custom painting is done by overriding the paintComponent() method of a JPanel or JComponent. I suggest you start by reading the Swing tutorial on Custom Painting for a working example.

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

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