使用JavaFX从图像阵列列表进行幻灯片放映
我正在尝试创建一个幻灯片,通过使用使用JavaFX从图像阵列列表进行幻灯片放映,java,arraylist,javafx,Java,Arraylist,Javafx,我正在尝试创建一个幻灯片,通过使用for循环,获取图像的阵列列表,并将它们放入图像视图。但是,为了“暂停”程序,使每个图像都可见,我尝试使用Thread.sleep。不幸的是,这并没有达到预期的效果。为了解决这个问题,我没完没了地在谷歌上搜索,这让我怀疑我应该使用Timeline类,但我不知道如何实现它。任何帮助都将不胜感激。目前我的功能失调代码如下所示: for (int i = 0; i < imageArrayList.size(); i++) { try {
for
循环,获取图像的阵列列表
,并将它们放入图像视图
。但是,为了“暂停”程序,使每个图像都可见,我尝试使用Thread.sleep
。不幸的是,这并没有达到预期的效果。为了解决这个问题,我没完没了地在谷歌上搜索,这让我怀疑我应该使用Timeline
类,但我不知道如何实现它。任何帮助都将不胜感激。目前我的功能失调代码如下所示:
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));
}
for(int i=0;i
使用计时器
每特定毫秒更新一次图像
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);
另外,
slideshowImageView
和imageArrayList
必须是字段或final
变量,才能在“TimerTask”中访问。在长时间的谷歌搜索后发现了它
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();
});
int计数//声明为全局变量
//然后是eventhandler中的工作逻辑
任务=新任务(){
@凌驾
public Void call()引发异常{
对于(int i=0;i=imageArrayList.size()){
幻灯片放映计数=0;
}
}
});
睡眠(1000);
}
返回null;
}
};
线程th=新线程(任务);
th.setDaemon(true);
th.start();
});
对JafaFx中的并发性进行一些研究,您需要设置某种计时器,它将在GUI线程的上下文中触发回调方法。我在下面发布了一个答案,请让我知道它是否有帮助。请注意,感谢您的快速响应,但您的代码在线程“timer-2”中出现了此错误code
异常线程“Timer-10”中的异常线程“Timer-6”中的异常线程“Timer-0”中的异常线程“Timer-8”中的异常线程“Timer-5”中的异常java.lang.IllegalStateException:不在FX应用程序线程上;currentThread=Timer-8code
@agelston好的,完整堆栈跟踪是什么?你知道问题出在哪里吗?粘贴完整的堆栈跟踪,我将修复我的答案(另外,您能告诉我,“new Timer().schedule(new TimerTask(){)”的行号是多少吗你的.java文件中有行吗?谢谢,伙计,你得原谅我的无知。我可能有点不知所措……全堆栈跟踪,你的意思是这样的吗?新的计时器语句是在线的244@agelston我认为这是因为计时器循环超出了数组的边界,所以在某个时候,它试图从lis中获取图像id不存在的t。赋值是包/类