如何在一个圆圈中制作java形状动画?
问题描述:
我正在试图在画布中的一个圆圈内移动一个正方形。我已经得到了一个方框在框架内来回移动,但我在布置圆周运动时遇到了一些困难。我创建了一个变量theta,其中摆动计时器发生变化,因此改变了形状的整体位置。但是,当我运行它时,没有任何反应我也不确定是否应该使用双精度或整数,因为drawRectangle命令只接受整数,但数学足够复杂,需要双精度值。这是我到目前为止有:如何在一个圆圈中制作java形状动画?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Circle extends JPanel implements ActionListener{
Timer timer = new Timer(5, this);
Double theta= new Double(0);
Double x = new Double(200+(50*(Math.cos(theta))));
Double y = new Double(200+(50*(Math.sin(theta))));
Double change = new Double(0.1);
int xp = x.intValue();
int yp = y.intValue();
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(xp, yp, 50, 50);
timer.start();
}
public void actionPerformed(ActionEvent e) {
theta=theta+change;
repaint();
}
public static void main(String[] args){
Circle a = new Circle();
JFrame frame = new JFrame("Circleg");
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(a);
}
}
答
theta=theta+change;
repaint();
你不改变XP,YP值。他们不会因为theta值的变化而自我更新自己。
将计算x/y位置的代码移动到paintComponent()方法中。
Double x = new Double(200+(50*(Math.cos(theta))));
Double y = new Double(200+(50*(Math.sin(theta))));
int xp = x.intValue();
int yp = y.intValue();
g.fillRect(xp, yp, 50, 50);
此外,
timer.start();
在画法不启动定时器。绘画方法仅适用于绘画。
定时器应该在你的类的构造函数中启动。