简体   繁体   English

如何使一个Java形状在一个圆圈中动画?

[英]How to make a java shape animate in a circle?

I'm trying to animate a square moving in a circle within the canvas. 我正在尝试为在画布内绕圆运动的正方形设置动画。 I have gotten a square to move back and forth within the frame but I'm having some difficulty laying out the circular motion. 我已经有了一个可以在框架内来回移动的正方形,但是在布置圆周运动时遇到了一些困难。 I created a variable theta which changes of a swing timer, therefore altering the overall position of the shape. 我创建了一个变量theta,该变量theta改变了摆动计时器,因此改变了形状的整体位置。 However when I run it nothing happens. 但是,当我运行它时,什么也没有发生。 I'm also not sure if I should be using doubles or ints since the drawRectangle command only accepts ints but the math is complex enough to require double values. 我也不确定是否应该使用double或int,因为drawRectangle命令仅接受int,但是数学很复杂,需要double值。 Here's what I have so far: 这是我到目前为止的内容:

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();

You don't change the xp, yp values. 您无需更改xp,yp值。 They will not magically update themselves just because the theta value changes. 他们不会仅仅因为theta值改变而神奇地更新自己。

Move the code calculating the x/y location right into the paintComponent() method. 将计算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);

Also, 也,

timer.start();

Do NOT start the Timer in the painting method. 不要以绘画方法启动计时器。 Painting methods are for painting only. 绘画方法仅用于绘画。

The Timer should be started in the constructor of your class. Timer应该在您的类的构造函数中启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM