我正在尝试用Java创建一个简单的动画,它显示一个蓝色的球,在500 x 500的窗口中水平移动。球应该以1px / 30ms的速度移动。问题是,窗口仅在while循环退出时被绘制,而不是在我想要的while循环的每次迭代期间。这导致蓝色球被涂在其最终位置。你能告诉我这里我做错了什么吗?我也尝试使用paintComponent()方法在EDT上执行此代码,并得到相同的结果。另外,正如其他帖子所建议的那样,当使用paintImmediately(0,0,getWidth(),getHeight())而不是repaint()时,我使用EDT和paintComponent()方法得到了相同的结果。我试图在不使用计时器的情况下完成所有这些工作。
import javax.swing.*;
import java.awt.*;
class AnimationFrame extends JPanel {
int ovalX = 50;
long animDuration = 5000;
long currentTime = System.nanoTime() / 1000000;
long startTime = currentTime;
long elapsedTime = currentTime - startTime;
public AnimationFrame() {
setPreferredSize(new Dimension(500, 500));
runAnimation();
}
public void runAnimation() {
while (elapsedTime < animDuration) {
currentTime = System.nanoTime() / 1000000;
elapsedTime = currentTime - startTime;
System.out.println(elapsedTime);
ovalX = ovalX + 1;
try {
Thread.sleep(30);
}
catch (Exception e) {
}
repaint();
}
}
public void paint(Graphics g) {
Rectangle clip = g.getClipBounds();
g.setColor(Color.BLACK);
g.fillRect(clip.x, clip.y, clip.width, clip.height);
g.setColor(Color.BLUE);
g.fillOval(ovalX, 250, 70, 70);
}
public static void main(String[] args) {
createAndShowGUI();
}
public static void createAndShowGUI() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new AnimationFrame());
mainFrame.pack();
mainFrame.setVisible(true);
}
}
答案 0 :(得分:4)
我查看了你的代码并注意到你正在调用“AnimationFrame”的构造函数中运行动画的方法,你将添加到“mainFrame”中。
这样做的问题在于,您要在对象构建完成之前尝试动画,必须先将其完成,然后才能将其添加到mainFrame中,而mainFrame尚未在屏幕上显示。
我对你的代码进行了以下更改,现在我看到一个蓝色的球在框架中移动。
import javax.swing.*;
import java.awt.*;
class AnimationFrame extends JPanel {
int ovalX = 50;
long animDuration = 5000;
long currentTime = System.nanoTime() / 1000000;
long startTime = currentTime;
long elapsedTime = currentTime - startTime;
public AnimationFrame() {
setPreferredSize(new Dimension(500, 500));
//i removed the call to runAnimation from here
}
public void runAnimation() {
while (elapsedTime < animDuration) {
currentTime = System.nanoTime() / 1000000;
elapsedTime = currentTime - startTime;
System.out.println(elapsedTime);
ovalX = ovalX + 1;
try {
Thread.sleep(30);
}
catch (Exception e) {
}
repaint();
}
}
@Override
public void paint(Graphics g) {
Rectangle clip = g.getClipBounds();
g.setColor(Color.BLACK);
g.fillRect(clip.x, clip.y, clip.width, clip.height);
g.setColor(Color.BLUE);
g.fillOval(ovalX, 250, 70, 70);
}
public static void main(String[] args) {
createAndShowGUI();
}
public static void createAndShowGUI() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AnimationFrame animationPanel = new AnimationFrame();
mainFrame.add(animationPanel);
mainFrame.pack();
mainFrame.setVisible(true);
//I made the call to runAnimation here now
//after the containing frame is visible.
animationPanel.runAnimation();
}
}
答案 1 :(得分:1)
您需要在单独的线程中执行循环。请参阅本教程 - http://101.lv/learn/Java/ch10.htm