简体   繁体   中英

javafx - Changing the image of an ImageView using timeline doesn't work

I want to display a sprite animation using an ImageView as a container for the images and a TimeLine to switch the images in the imageview:

private ImageView imgView;
...
public void init(Image[] images) {
   this.imgView = new ImageView(images[0]);
   Timeline timeLine = new Timeline();
   Collection<KeyFrame> frames = timeLine.getKeyFrames();
   for (Image img : images)
       frames.add(new KeyFrame(Duration.millis(256), e -> imgView.setImage(img)));

   timeLine.setCycleCount(Timeline.INDEFINITE);
   timeLine.play();
}

The ImageView is rendered, but is stuck on some image of the animation (and not even the first one). It is like I would have put just the one image into the imageview and never change it. I added a ChangeListener to the imageproperty of the ImageView outputing the current image of the imageview. And it is indeed changing as wanted, but still only one image is rendered. The images are definitely different, I doublechecked that. Why is the imageview not updated when the imageproperty changed?

You are using the same timepoint for all of the keyframes, so all of the calls to imgView.setImage(...) occur at the "same time". Only the last such call will have any visible effect, since there is no time in between the preceding calls.

You need to make each change of the image view's image happen at a different time. Something like:

public void init(Image[] images) {
    this.imgView = new ImageView(images[0]);
    Timeline timeLine = new Timeline();
    Collection<KeyFrame> frames = timeLine.getKeyFrames();
    Duration frameGap = Duration.millis(256);
    Duration frameTime = Duration.ZERO ;
    for (Image img : images) {
        frameTime = frameTime.add(frameGap);
        frames.add(new KeyFrame(frameTime, e -> imgView.setImage(img)));
    }
    timeLine.setCycleCount(Timeline.INDEFINITE);
    timeLine.play();
}

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