2

I am learning JavaFX. I want to display some icons one by one after few seconds. My code is not working. I have written some code. and icons are stored in a separate folder called images.

public class Main extends Application {
  ImageView imv;   
  Scene scene;

  @Override
  public void start(Stage primarystage) {
      gp=new GridPane();
      gp.setPadding(new Insets(0, 10, 10, 10));
      ...
      gp.setVgap(0);
      gp.setHgap(5);

      imv=new ImageView();

      // logic for displaying images

      scene=new Scene(gp, 450, 300, Color.TRANSPARENT);

      primarystage.setScene(scene);
      primarystage.setTitle("WINDOW");
      primarystage.show();
  }
  public static void main(String[] args) {
        launch(args);
  }
}

I couldn't find proper answers on web. I want to know the logic how it is done, what else I need to know. Because a single image I can easily display. But I don't know how to display multiple images one-by-one.

1 Answers1

2

Alright, I've tried something for you. I don't know what exactly you're looking for but this code will give you some idea at least. I've made few assumptions. You've a folder under the same directory with the name images which has all your icons (to be displayed) as 1.png, 2.png, 3.png, and so on. I'm using Netbeans 8.2 which will automatically import necessary classes from the respective packages.

import javafx.application.Application;
import javafx.concurrent.Task;
...
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
...

public class Main extends Application {

  ImageView imv;
  Label label;
  String file="";

  GridPane gridPane;
  Scene scene;
  Task<Void> slideShow;

  @Override
  public void start(Stage primarystage) {
    gridPane=new GridPane();
    gridPane.setPadding(new Insets(0, 10, 10, 10));

    // business logic for slide show 
    startSlideShow();

    imv=new ImageView();

    label = new Label();
    label.setGraphic(imv);   

    gridPane.add(label, 5, 0, 1, 1);      

    scene=new Scene(gridPane, 450, 300, Color.TRANSPARENT);

    primarystage.setScene(scene);
    primarystage.show();

    // spawning a new thread for this task
    new Thread(slideShow).start();
  }

  public void startSlideShow() {
    slideShow= new Task<Void>() {
      @Override
      protected Void call() {
        int i = 1;
        while (true) {
          try {
            Thread.sleep(1000);
            updateMessage(i + ".png");
          } catch (Exception e) {
          }
          i++;
        }
      }
     };
     task1.messageProperty().addListener((observable, oldValue, newValue) -> {
       Image image = new Image(getClass().getResourceAsStream("images/" + newValue));
       imv.setImage(image);
      });
    }

    public static void main(String[] args) {
      launch(args);
    }
}

Hope this will work You can customize the code according to your requirements.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110