user5531310
user5531310

Reputation: 15

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

}

}

Upvotes: 1

Views: 2272

Answers (1)

camickr
camickr

Reputation: 324207

theta=theta+change;
repaint();

You don't change the xp, yp values. They will not magically update themselves just because the theta value changes.

Move the code calculating the x/y location right into the paintComponent() method.

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.

Upvotes: 1

Related Questions