javafx animation looping


in c++ or c programming language, we know to change the cordinate we use gotoxy(x,y) and we can use looping and sleep to change the cordinate and making animation. like this;

for(x = 20; x < 25; x++){
  gotoxy(x,20); cout << "*"

but my queston is how about in JAVAFX 2.0 programming? i'm using netbeans 7.2. thanks for your any help.

10/23/2012 12:08:06 PM

Accepted Answer

Have look at using a Timeline Animation. It is a key component of animation in JavaFX and
is used to establish when, and in what sequence, key parts of an animation occur.

Here is an example

5/13/2013 10:11:34 PM

Use the JavaFX Animation Package.

There are numerous examples in the JavaFX Animation Tutorial, as Andy pointed out in his comment.

And there is a cute example of a running horse animation loop.

The key is that you don't sleep the JavaFX application thread and you have to release control of the JavaFX thread back to the JavaFX system each time you update something and want it rendered. The JavaFX animation classes take care of these things for you so that you don't have to worry about it. If you just loop like you do in the sample code from your question, JavaFX will just render the scene once after your loop has completed and you will never see anything happen.

Here is a fairly boring example which uses a Timeline to emulate the c++ code in your question to move a dot a pixel every 400 milliseconds.

import java.util.Date;
import javafx.animation.*;
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

/** Simple JavaFX Animation Sample. */
public class AnimationSample extends Application {
  private       int         x        = 20;
  private       String      status   = "";
  private final Circle      dot      = new Circle(20, 20, 3);
  private final TimeCounter counter  = new TimeCounter();

  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final Timeline timeline = new Timeline(
      new KeyFrame(Duration.ZERO, new EventHandler() {
        @Override public void handle(Event event) {
      new KeyFrame(Duration.millis(400))

    stage.setScene(new Scene(new Group(dot), 50, 50));;


  private void refreshScene() {
    gotoxy(x, 20);

    status = "*****".equals(status) ? "*" : status + "*";
    System.out.println(String.format("%7d", counter.elapsed()) + " ms " + x + " " + status);

    if (x == 24) {
      x = 20;
    } else {

  private void gotoxy(int x, int y) {

  class TimeCounter {
    private long start = new Date().getTime();
    void reset()   { start = new Date().getTime(); }
    long elapsed() { return new Date().getTime() - start; }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow