JavaFx implements image carousel (1)

        After I published the articleA Java-implemented explosive tool ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ or  but I have recently several private messages to me. To achieve the image carousel effect, let’s take you through a simple image carousel effect.

        JavaFX can use ImageView and Timeline to implement image carousel. ImageView is used to display pictures, and Timeline is used to control the time of picture switching. A simple sample code is given below.

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ImageSlider extends Application {

    private int currentIndex = 0;

    private ImageView[] images = {
            new ImageView(new Image("image1.jpg")),
            new ImageView(new Image("image2.jpg")),
            new ImageView(new Image("image3.jpg"))
    };

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(images);

        Timeline timeline = new Timeline(new KeyFrame(
                Duration.seconds(2), event -> {
                    currentIndex = (currentIndex + 1) % images.length;
                    for (int i = 0; i < images.length; i++) {
                        images[i].setVisible(i == currentIndex);
                    }
                }));

        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();

        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

In this code, three ImageView objects are first defined to display three pictures. Then use the Timeline class to control the switching of pictures, switching pictures every two seconds. The currentIndex variable is used to record the index of the currently displayed image, and switches images by looping through all ImageView objects to set their visibility. Finally, add the ImageView object to the StackPane and display the StackPane as the root node of the scene. Run the program and you can see the effect of the picture carousel.

Guess you like

Origin blog.csdn.net/m0_37649480/article/details/134923232