Java 如何在线程和小程序中使用双缓冲
我有一个关于何时调用绘制和更新方法的问题?? 我有一个游戏小程序,我想使用双缓冲。但我不能使用它。问题是 在我的游戏中,有一个球在run()方法中移动。我想知道如何使用双缓冲来交换屏幕外图像和当前图像。有人请帮忙Java 如何在线程和小程序中使用双缓冲,java,Java,我有一个关于何时调用绘制和更新方法的问题?? 我有一个游戏小程序,我想使用双缓冲。但我不能使用它。问题是 在我的游戏中,有一个球在run()方法中移动。我想知道如何使用双缓冲来交换屏幕外图像和当前图像。有人请帮忙 当同时存在update()和paint()方法时,首先调用哪一个,何时以及为什么 您可以使用的一种方法是向小程序添加画布,然后为该画布创建缓冲策略。抽象代码,您可能会得到硬件加速 代码如下:--扩展AppletGameCore并定义实现所需方法的您自己的子类 import java.a
当同时存在update()和paint()方法时,首先调用哪一个,何时以及为什么 您可以使用的一种方法是向小程序添加画布,然后为该画布创建缓冲策略。抽象代码,您可能会得到硬件加速 代码如下:--扩展AppletGameCore并定义实现所需方法的您自己的子类
import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.image.BufferStrategy;
import java.applet.Applet;
/**
*AppletGameCore.java
*@author David Graham
*/
public abstract class AppletGameCore extends Applet implements Runnable
{
private BufferStrategy bufferStrategy;
private Canvas drawArea;/*Drawing Canvas*/
private boolean stopped = false;/*True if the applet has been destroyed*/
private int x = 0;
public void init()
{
Thread t = new Thread(this);
drawArea = new Canvas();
setIgnoreRepaint(true);
t.start();
}
public void destroy()
{
stopped = true;
/*Allow Applet to destroy any resources used by this applet*/
super.destroy();
}
public void update()
{
if(!bufferStrategy.contentsLost())
{
//Show bufferStrategy
bufferStrategy.show();
}
}
//Return drawArea's BufferStrategy
public BufferStrategy getBufferStrategy()
{
return bufferStrategy;
}
//Create drawArea's BufferStrategies
public void createBufferStrategy(int numBuffers)
{
drawArea.createBufferStrategy(numBuffers);
}
//Subclasses should override this method to do any drawing
public abstract void draw(Graphics2D g);
public void update(Graphics2D g)
{
g.setColor(g.getBackground());
g.fillRect(0,0,getWidth(),getHeight());
}
//Update any sprites, images, or primitives
public abstract void update(long time);
public Graphics2D getGraphics()
{
return (Graphics2D)bufferStrategy.getDrawGraphics();
}
//Do not override this method
public void run()
{
drawArea.setSize(new Dimension(getWidth(),getHeight()));
add(drawArea);
createBufferStrategy(2);
bufferStrategy = drawArea.getBufferStrategy();
long startTime = System.currentTimeMillis();
long currTime = startTime;
//animation loop
while(!stopped)
{
//Get time past
long elapsedTime = System.currentTimeMillis()-currTime;
currTime += elapsedTime;
//Flip or show the back buffer
update();
//Update any sprites or other graphical objects
update(elapsedTime);
//Handle Drawing
Graphics2D g = getGraphics();
update(g);
draw(g);
//Dispose of graphics context
g.dispose();
}
}
}