agelston
agelston

Reputation: 41

Slideshow from an ArrayList of images with JavaFX

I'm trying to create a slideshow by taking an ArrayList of images and putting them into an ImageView using a for loop. However, in order to "pause" the program so that each image will be visible, I am trying to use Thread.sleep. This unfortunately hasn't had the desired effect. In trying to remedy this, my endless googling leads me to suspect that I should be using the Timeline class, but I have no idea how to implement it. Any help would be much appreciated. My dysfunctional code as it stands looks like this:

for (int i = 0; i < imageArrayList.size(); i++) {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        System.out.println("Error: " + e.toString());
    }
    slideshowImageView.setImage(imageArrayList.get(i));
}

Upvotes: 2

Views: 5462

Answers (2)

agelston
agelston

Reputation: 41

Figured it after a good long while of googling

    int count; //declared as global variable         



//then the working logic in my eventhandler
    Task task = new Task<Void>() {
            @Override
            public Void call() throws Exception {
                 for (int i = 0; i < imageArrayList.size(); i++) {
                     Platform.runLater(new Runnable() {
                         @Override
                         public void run() {
                              slideshowImageView.setImage(imageArrayList.get(slideshowCount));
                              slideshowCount++;
                              if (slideshowCount >= imageArrayList.size()) {
                                  slideshowCount = 0;
                              }
                         }
                      });

                     Thread.sleep(1000);
                  }
                  return null;
            }
            };
            Thread th = new Thread(task);
            th.setDaemon(true);
            th.start();

    });

Upvotes: 2

Victor2748
Victor2748

Reputation: 4199

Use a Timer to update the image once per certain amount of milliseconds

public int count = 0;

// then in your method

long delay = 2000; //update once per 2 seconds.
new Timer().schedule(new TimerTask() {

    @Override
    public void run() {
        slideshowImageView.setImage(imageArrayList.get(count++));
        if (count >= imageArrayList.size() {
            count = 0;
        }
    }
}, 0, delay);

Also, slideshowImageView and imageArrayList must be either fields, or final variables, to be accessed inside the `TimerTask.

Upvotes: 1

Related Questions