Java JApplet Graphics Double Buffering

爱⌒轻易说出口 提交于 2019-12-11 06:58:11

问题


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.

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

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.


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/5371979/java-japplet-graphics-double-buffering

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