问题描述
我需要在程序运行时不断在不同位置重绘特定图像.因此,我设置了一个while循环,该循环应该在屏幕上移动图像,但是它只是一遍又一遍地重画图像.我究竟做错了什么?有没有办法在将新图像绘制到新位置之前将其删除?
I need a certain image to be redrawn at different locations constantly as the program runs. So I set up a while loop that should move an image across the screen, but it just redraws the image on top of itself over and over again. What am I doing wrong? Is there a way to delete the old image before drawing it in a new location?
JFrame frame = buildFrame();
final BufferedImage image = ImageIO.read(new File("BeachRoad_double_size.png"));
JPanel pane = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int num = 0;
boolean fluff = true;
while (fluff == true) {
num = num + 1;
g.drawImage(image, num, 0, null);
if (num == 105) {
fluff = false;
}
}
}
};
frame.add(pane);
推荐答案
您不能在paintComponent()方法中编写循环.该代码将执行得如此之快,以致只能在最终位置上绘制图像,在您的情况下,最终位置应为x位置105.
You can't code a loop in the paintComponent() method. The code will execute so fast that the image will only be painted in the final position, which in your case should be with an x position of 105.
相反,您需要使用Swing计时器每100毫秒左右安排一次动画.然后,当计时器触发时,您将更新x位置并在面板上调用repaint().阅读使用Swing计时器上的Swing教程,以获取更多信息.
Instead you need to use a Swing Timer to schedule the animation every 100 milliseconds or so. Then when the timer fires you update the x position and invoke repaint() on the panel. Read the Swing tutorial on Using Swing Timers for more information.
这篇关于Java .drawImage:如何“取消绘制";或删除图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!