1

I am trying a basic animation to move around a circle, but the stage is not showing the circle's new position.

package circler;

import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import javafx.scene.layout.*;
import javafx.util.Duration;

public class Main extends Application {
    Circle circle;
    int distance = 100;
    int angle = 0;

    public void start(Stage primaryStage) {
        circle = new Circle();
        circle.setCenterX(400);
        circle.setCenterY(400);
        circle.setRadius(10);
        circle.setFill(Color.RED);

        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.1), e -> {
                angle++;
                angle %= 360;
                setPosition();
                primaryStage.show();
        }));

        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();

        primaryStage.setScene(new Scene(new StackPane(circle), 800, 800));
        primaryStage.show();
    }

    private int calc(boolean sin) {
        return (int) (sin ? distance * Math.sin(Math.toRadians(angle)) : distance * Math.cos(Math.toRadians(angle)));
    }
    
    private void setPosition() {
        circle.setCenterX(circle.getScene().getHeight() / 2 + calc(true));
        circle.setCenterY(circle.getScene().getHeight() / 2 + calc(false));
        System.out.println(circle.getCenterX());
    }
}

I tried every page which tells about refreshing it. I want the circle to move 100ms and the stage should show it at the new position.

0009laH
  • 1,960
  • 13
  • 27
Tom O.
  • 11
  • 1
  • 3
    [This](https://stackoverflow.com/questions/9908402/rotate-orbit-node-around-another-object-javafx-2) may help. – SedJ601 Aug 05 '23 at 06:43
  • I am changing the position of the circle, not rotating it. – Tom O. Aug 05 '23 at 06:52
  • 1
    I did not run the code, but the linked question talks about rotating a circle around a rectangle. That would require changing position. – SedJ601 Aug 05 '23 at 07:19
  • 1
    Really, and it worx! THX!! – Tom O. Aug 05 '23 at 07:25
  • https://stackoverflow.com/questions/20022889/how-to-make-the-ball-bounce-off-the-walls-in-javafx#51561957 – SedJ601 Aug 05 '23 at 07:29
  • 4
    I would use a Group or Pane instead of a StackPane, then apply a RotateTransform with a pivot point, and have the animation modify the angle property of the transform l[like this](https://gist.github.com/jewelsea/1475424). But that is just me. If you made the StackPane solution work how you want and are happy with the solution, that is fine. – jewelsea Aug 05 '23 at 08:43
  • 4
    Another way to do this is a PathTransition with a circular path and an orientation of ORTHOGONAL_TO_TANGENT or NONE. Try it with a square on the animated path and different orientation types if interested. – jewelsea Aug 05 '23 at 08:52

0 Answers0