如何使 java 形状在一个圆圈中动画?
How to make a java shape animate in a circle?
我正在尝试为 canvas 内的一个圆圈移动的正方形制作动画。我有一个正方形可以在框架内来回移动,但我在布置圆周运动时遇到了一些困难。我创建了一个变量 theta 来改变摆动计时器,因此改变了形状的整体位置。但是,当我 运行 时,什么也没有发生。我也不确定我是否应该使用双精度数或整数,因为 drawRectangle 命令只接受整数,但数学非常复杂,需要双精度值。这是我目前所拥有的:
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();
不要在绘画方法中启动定时器。绘画方法只是为了绘画。
Timer 应该在 class.
的构造函数中启动
我正在尝试为 canvas 内的一个圆圈移动的正方形制作动画。我有一个正方形可以在框架内来回移动,但我在布置圆周运动时遇到了一些困难。我创建了一个变量 theta 来改变摆动计时器,因此改变了形状的整体位置。但是,当我 运行 时,什么也没有发生。我也不确定我是否应该使用双精度数或整数,因为 drawRectangle 命令只接受整数,但数学非常复杂,需要双精度值。这是我目前所拥有的:
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();
不要在绘画方法中启动定时器。绘画方法只是为了绘画。
Timer 应该在 class.
的构造函数中启动