我正在编写一个Java应用程序,该应用程序需要在屏幕上平滑滚动波形。我花了很长时间浏览各种教程,以找出如何使此动画尽可能平滑。据我所知,我已经完成了所有正常的操作以消除闪烁(一步一步绘制到屏幕外的缓冲区并进行渲染,再加上覆盖更新,以使屏幕不被遮挡),但是我的动画仍然闪烁,并且屏幕好像在每次更新之前都被清空了。
我确定我缺少一些基本的(可能很简单)的东西,但是我没有想法。我将在下面发布一个类来说明问题。任何帮助将非常感激。
import java.awt.*;
import javax.swing.*;
public class FlickerPanel extends JPanel implements Runnable {
private float [] pixelMap = new float[0];
/** Cached graphics objects so we can control our animation to reduce flicker **/
private Image screenBuffer;
private Graphics bufferGraphics;
public FlickerPanel () {
Thread t = new Thread(this);
t.start();
}
private float addNoise () {
return (float)((Math.random()*2)-1);
}
private synchronized void advance () {
if (pixelMap == null || pixelMap.length == 0) return;
float [] newPixelMap = new float[pixelMap.length];
for (int i=1;i<pixelMap.length;i++) {
newPixelMap[i-1] = pixelMap[i];
}
newPixelMap[newPixelMap.length-1] = addNoise();
pixelMap = newPixelMap;
}
public void run() {
while (true) {
advance();
repaint();
try {
Thread.sleep(25);
} catch (InterruptedException e) {}
}
}
private int getY (float height) {
double proportion = (1-height)/2;
return (int)(getHeight()*proportion);
}
public void paint (Graphics g) {
if (screenBuffer == null || screenBuffer.getWidth(this) != getWidth() || screenBuffer.getHeight(this) != getHeight()) {
screenBuffer = createImage(getWidth(), getHeight());
bufferGraphics = screenBuffer.getGraphics();
}
if (pixelMap == null || getWidth() != pixelMap.length) {
pixelMap = new float[getWidth()];
}
bufferGraphics.setColor(Color.BLACK);
bufferGraphics.fillRect(0, 0, getWidth(), getHeight());
bufferGraphics.setColor(Color.GREEN);
int lastX = 0;
int lastY = getHeight()/2;
for (int x=0;x<pixelMap.length;x++) {
int y = getY(pixelMap[x]);
bufferGraphics.drawLine(lastX, lastY, x, y);
lastX = x;
lastY = y;
}
g.drawImage(screenBuffer, 0, 0, this);
}
public void update (Graphics g) {
paint(g);
}
public static void main (String [] args) {
JFrame frame = new JFrame("Flicker test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new FlickerPanel());
frame.setSize(500,300);
frame.setVisible(true);
}
}
最佳答案
JPanel
中,覆盖paintComponent(Graphics)
而不是paint(Graphics)
Thread.sleep(n)
实现用于重复任务的Swing Timer
或用于长时间运行任务的SwingWorker
。有关更多详细信息,请参见Concurrency in Swing。
关于java - 如何消除Java动画闪烁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9859211/