我正在尝试使用 javaFX 创建一个显示图像的窗口 在一段时间内一次一个 我无法让图像循环播放或显示
垂直框显示为空
这是我最后一次尝试将 vbox child 添加到 vbox
有想法吗?我已经坚持了几个小时
package digitalframe;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.util.*;
import javafx.scene.image.Image;
import javafx.util.Duration;
import java.util.ArrayList;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
public class DigitalFrame extends Application {
@Override
public void start(Stage stage) throws Exception {
final ArrayList imageList = new ArrayList<>();
imageList.add(new ImageView("1.jpg"));
imageList.add(new ImageView("2.jpg"));
imageList.add(new ImageView("3.jpg"));
// Create the label and align its contents
final VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
// This is the keyframe handler.
class ImageHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
for (int n = 0; n > imageList.size(); n++) {
vBox.getChildren().add(new ImageView());
}
}
}
// Build the keyframe.
Duration sec = new Duration(1000);
ImageHandler image = new ImageHandler();
KeyFrame keyFrame = new KeyFrame(sec, image);
// Build the time line animation.
Timeline timeline = new Timeline(keyFrame);
timeline.setCycleCount(15);
// Set the stage and show, and play the animation
stage.setScene(new Scene(vBox, 250, 300));
stage.setTitle("Animation Counter");
stage.show();
timeline.playFromStart();
}
// @param args the command line arguments
public static void main(String[] args) {
launch(args);
}
}
最佳答案
首先需要区分ImageView
和 Image
. ImageView
是显示 Image
的场景图节点,Image
是实际图像(由 ImageView
显示) ). ImageView 是场景图的一部分,并显示它当前包含的图像。
因此,与其创建多个 ImageView
对象,不如只创建一个,并为您的图像创建 Image
对象:
...
final List<Image> imageList = new ArrayList<>();
// create Image objects for each image
imageList.add(new Image("1.jpg"));
imageList.add(new Image("2.jpg"));
imageList.add(new Image("3.jpg"));
// Create the label and align its contents
final VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
ImageView imageView = new ImageView(); // create only one ImageView
vBox.getChildren().add(imageView); // and add it to the scene graph
...
然后,在您的处理程序中,每次调用处理程序时设置下一张图像:
@Override
public void handle(ActionEvent event) {
imageView.setImage(imageList.get(idx++));
if (idx >= imageList.size()) {
idx = 0;
}
}
您不能遍历处理程序中的所有图像,因为会为每一帧调用处理程序 - 然后,对于每一帧,您可以显示下一张图像。请注意,idx
变量必须声明为字段变量,因为您不能在闭包中使用非最终局部变量:
...
private int idx = 0;
...
关于javaFX 帧图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35860990/