简体   繁体   中英

Give an image a new X and Y postion every 1 second

I am trying change the image LayoutX and LayoutY positions ever 1 second. But I cant find any (timer) method suitable for this. I am looking for something similar to the JavaScript "setInterval" that simply lets me create a "timer cycle" using Java or JavaFX.

Any advice are widely appriciated!

With java.util.Timer you can schedule such a task.

The method timer.schedule() executes a task only ones. To repeat your task use the method timer.scheduleAtFixedRate() .

 Timer timer = new Timer();
 timer.scheduleAtFixedRate(new TimerTask() {

   @Override
   public void run() {
        System.out.println("hello");
   }
 }, 1000, 1000);

The second parameter of scheduleAtFixedRate() is the delay before the first execution in milliseconds and the last parameter is the interval between the tasks being executed in milliseconds.

You can use a Timeline with INDEFINITE cycle count for this purpose.

Example:

Timeline tl = new Timeline(new KeyFrame(Duration.seconds(1), evt -> {
    // toggle image postion
    imageView.setLayoutX(200 - imageView.getLayoutX());
    imageView.setLayoutY(200 - imageView.getLayoutY());
}));
tl.setCycleCount(Animation.INDEFINITE);
tl.play();

This guaranties the event handler runs on the JavaFX application thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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