简体   繁体   中英

How do you add a tick to javafx?

I was wondering how to add a tick to javafx. By tick i mean a repetitive thread that updates the scene. I have tried an normal thread but I keep getting error that is is not the application thread. I would like it to start in the initialize method here is a heavily simplified version of my MainContol class:

package application;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.Initializable;

public class MainControl implements Initializable{
    public void initialize(URL arg0, ResourceBundle arg1) {
          // Tick goes here
    }
}

I think what you are looking for is a Timeline. A timeline creates a thread that repeats a set amount of times or infinitely until you terminate it.
Here is how you would at it:

MainControl:

package application;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.Initializable;
import javafx.util.Duration;

@SuppressWarnings("deprecation")
public class MainControl implements Initializable{
    public void initialize(URL arg0, ResourceBundle arg1) {
    Timeline tick = TimelineBuilder.create()//creates a new Timeline
     .keyFrames(
       new KeyFrame(
            new Duration(10),//This is how often it updates in milliseconds
            new EventHandler<ActionEvent>() {
                  public void handle(ActionEvent t) {
                       //You put what you want to update here
                  }
            }
        )
     )
    .cycleCount(Timeline.INDEFINITE)
    .build();
tick.play();//Starts the timeline
    }
}

I hope this helps

If you happen to use Java 8, here is the same thing using ReactFX :

public class MainControl implements Initializable{
    public void initialize(URL arg0, ResourceBundle arg1) {
        EventStreams.ticks(Duration.ofMillis(10)).subscribe(() -> {
            //You put what you want to update here
        });
    }
}

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