我正在尝试做一个简单的程序,其中一个球在JFrame中通过Canvas移动。 我希望主线程更新屏幕中球的位置并在画布上打印每个帧,而另一个线程更新缓冲区上的每个下一帧。这是我的代码:
public class SynchAnimation {
private JFrame frame;
private Canvas canvas;
private BufferedImage frameImage;
private Graphics bfg;
private final int width = 500, height = 500;
private int x, y;
private DrawingThread drawingThread;
private final Object key;
public SynchAnimation() {
key = new Object();
x = 200;
y = 200;
frame = new JFrame("Synchronized animation");
frame.setSize(width, height);
frame.setLocationRelativeTo(null);
frameImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bfg = frameImage.createGraphics();
canvas = new Canvas() {
@Override
public void paint(Graphics g) {
g.drawImage(frameImage, 0, 0, null);
}
};
canvas.setSize(width, height);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
}
public void mainRun() {
drawingThread = new DrawingThread();
drawingThread.start();
while (true) {
synchronized (key) {
x += 1;
y += 1;
canvas.repaint();
}
}
}
class DrawingThread extends Thread {
@Override
public void run() {
while (true) {
synchronized (key) {
bfg.clearRect(0, 0, width, height);
bfg.setColor(Color.BLUE);
bfg.fillRect(0, 0, width, height);
bfg.setColor(Color.ORANGE);
bfg.fillOval(x, y, 40, 40);
}
}
}
}
public static void main(String[] args) {
new SynchAnimation().mainRun();
}
为什么它仍然像地狱一样闪烁?我认为同步块可以解决问题。这实际上不是一个GUI问题,它是一个线程问题......我这样做是为了理解同步线程在尝试访问和修改相同数据时的工作方式。 谢谢你的帮助!
答案 0 :(得分:0)
您可能希望覆盖paintComponent()而不是