我在网上找到了一些Java游戏代码,我正在尝试修改它。我将它从 JFrame 转换为 Applet,但每次重新绘制屏幕时我的游戏开始闪烁。我试过双缓冲但没有区别。
来源:
private void paintDisks(Graphics g) {
try {
for (Disk d : disk)
paintDisk(g, d);
} catch (Exception ex) {
//System.out.println(ex.getMessage());
paintDisks(g); // retry so the disks never not get painted
}
}
private void paintDisk(Graphics g, Disk d) {
if (d == null)
return;
if (diskimg[d.player] == null) {
g.setColor(colour[d.player]);
g.fillOval((int)d.x - 1, (int)d.y - 1, 32, 32);
} else {
g.drawImage(diskimg[d.player],
(int)d.x - 1, (int)d.y - 1,
32, 32, this);
}
}
@Override
public void paint(Graphics g) {
// paint real panel stuff
super.paint(g);
Graphics gr;
if (offScreenBuffer==null ||
(! (offScreenBuffer.getWidth(this) == this.size().width
&& offScreenBuffer.getHeight(this) == this.size().height)))
{
offScreenBuffer = this.createImage(size().width, size().height);
}
gr = offScreenBuffer.getGraphics();
gr.clearRect(0,0,offScreenBuffer.getWidth(this),offScreenBuffer.getHeight(this));
// paint the disks
paintDisks(gr);
// paint the curser ontop of the disks
paintCurser(gr);
g.drawImage(offScreenBuffer, 0, 0, this);
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(9, 1);
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
}
}
}
最佳答案
简短回答:不要在您的 Board.paint()
方法中调用 super.paint()
。
长答案:Applet 也是一个容器,它有自己的显示属性,包括您通过 setBackground(Color.WHITE);
设置的背景颜色作为构造函数的一部分.通过调用 super.paint(g)
,您将导致 applet 将其白色背景绘制到显示图形上,并调用任何包含的组件绘制。这就是闪烁的原因 - 每个绘制周期,它都会将屏幕显示绘制为白色,然后将 offscreenBuffer
图像复制到屏幕显示。
可能最好明确一点,忘记 Applet 背景,删除 super.paint(g)
,然后自己完成所有绘制步骤。您需要将 clearRect()
替换为 setColor()
和 fillRect()
。
此外,您还应该实现 update()
。
@Override
public void update(Graphics g) { paint(g); }
@Override
public void paint(Graphics g) {
// no super.paint(g)
if (offScreenBuffer==null ||
(! (offScreenBuffer.getWidth(this) == this.size().width
&& offScreenBuffer.getHeight(this) == this.size().height)))
{
offScreenBuffer = this.createImage(size().width, size().height);
}
Graphics gr = offScreenBuffer.getGraphics();
// blank the canvas
gr.setColor(Color.WHITE);
gr.fillRect(0,0,offScreenBuffer.getWidth(this),offScreenBuffer.getHeight(this));
// paint the disks
paintDisks(gr);
// paint the curser ontop of the disks
paintCurser(gr);
g.drawImage(offScreenBuffer, 0, 0, this);
}
关于java - 为什么每次重绘时我的小程序都会闪烁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6775315/