Java AWT rotating ball

Oh boy, trigonometry is so hard! I kinda need some help, It's a simple program that is supposed to rotate a ball around the center of the screen... Here is my code:

import java.awt.*;

import javax.swing.*;

public class Window {
private int x;
private int y;
private int R = 30;
private double alpha = 0;

private final int SPEED = 1;
private final Color COLOR =;

public static void main(String[] args) {    
    new Window().buildWindow();

public void buildWindow() {
    JFrame frame = new JFrame("Rotation");
    frame.add(new DrawPanel());
    while(true) {
        try {
            alpha += SPEED;
        } catch (InterruptedException e) {


class DrawPanel extends JPanel {

    public void paintComponent(Graphics g) {
        Font font = new Font("Arial",Font.PLAIN,12);
        g.drawString(String.format("Angle: %.2f ", alpha), 0, 12);

        g.drawLine(this.getWidth()/2,0, this.getWidth()/2, this.getHeight());
        g.drawLine(0, this.getHeight()/2, this.getWidth(), this.getHeight()/2);

        x = (int) ((this.getWidth() / 2 - R / 2 ) + Math.round((R + 20) * Math.sin(alpha)));
        y = (int) ((this.getHeight() / 2 - R / 2 ) + Math.round((R + 20) * Math.cos(alpha)));

        g.fillOval(x, y, R, R);

This code looks like it's working, but then I've printed Angle[alpha] information to the screen. And when I comment out the alpha+=SPEED and enter the angle manually it does not look like it's working.The angle on the screen doses not correspond to that angle alpha. So I need suggestions. What should I change? Is my trigonometry wrong? etc...


Three things to note here:

  1. I assume your alpha variable is in degrees since you are adding 20 in each step. However the Math.sin() and Math.cos() methods expect an angle in radians.
  2. Normally 0 deg (or 0 rads) is represented at the "3 o'clock" position. For this you need to switch the sin and cos calls.
  3. Reverse the sign in the y equation to account for the fact that y coordinates start at the top of the screen and increase downwards

With these modifications, your code will work as you expect:

double rads = (alpha * Math.PI) / 180F;
x = (int) ((this.getWidth() / 2 - R / 2 ) + Math.round((R + 20) * Math.cos(rads)));
y = (int) ((this.getHeight() / 2 - R / 2 ) - Math.round((R + 20) * Math.sin(rads)));

Need Your Help

how to edit local notifications in iphone sdk objective c

ios objective-c iphone xcode6 uilocalnotification

I am working on a dummy project in xcode 6 and creating local notifications. I have created and deleted these local notifications.Now I want to edit a particular notification.