我正在尝试为 Canvas 内的一个圆形移动的正方形设置动画。我已经得到了一个可以在框架内来回移动的正方形,但我在布置圆周运动时遇到了一些困难。我创建了一个变量 theta,它会改变 Swing 计时器,从而改变形状的整体位置。但是当我运行它时什么也没有发生。我也不确定是否应该使用 double 或整数,因为 drawRectangle 命令只接受整数,但数学足够复杂,需要 double 值。这是我到目前为止所拥有的:
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();
不要在绘画方法中启动计时器。绘画方法仅用于绘画。
计时器应该在类的构造函数中启动。
关于java - 如何使java形状以圆形动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584554/