我正在嘗試創建類似資訊螢屏的內容,該螢屏僅滾動瀏覽使用我撰寫的小型管理應用程式上傳的影像(也許有一天 pdf)。
一些看完后我想我明白為什么我應該不具備的Thread.sleep在我的for回圈。我在 stackoverflow 和其他頁面上閱讀了一些帖子,這些帖子教我不要這樣做。
顯然我應該將ExecutorService用于這樣的事情,但我無法理解它。
所以在準備好我的 GUI 和其他所有東西之后,我終于呼叫了我的 showImages 并保持在這個 while 回圈中。每次回圈后,我都會從檔案系統重新加載記錄,因此任何更改都會顯示在螢屏上。
我創建了一個元檔案,其中包含每個影像的首選延遲,并且只是睡眠一段時間。
private void showImages() {
//noinspection InfiniteLoopStatement
while (true) {
loadRecords();
for (ImageRecord record : records) {
System.out.println("Showing: " record.getFilename());
imageLabel.setIcon(record.getIconForInfoScreen(screenWidth, screenHeight));
int delay = record.getDurationAsInt();
System.out.println("Waiting for " delay " milliseconds");
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
所以如果我理解正確,我可以使用類似的東西
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(showImage(),0, delay, TimeUnit.MILLISECONDS);
但這會每“延遲”毫秒觸發一次 showImage() ,我仍然需要增加一些計數器,以獲取記錄中的下一個影像。
有人能把我推向正確的方向嗎?我現在有點迷茫。
uj5u.com熱心網友回復:
關于我的問題的所有評論都可以被認為是好主意,其中一個也引導我得出最終結果。但最后,問題是,我不明白如何在我的回圈中實作一個計時器。
或者換句話說,回圈必須消失,而是使用計數器并為計時器回圈內的后續記錄設定延遲。
private void loopImages() {
loadRecords();
recordSize = records.size();
int delay = records.get(1).getDurationAsInt();
timer = new Timer(delay, e -> showImages());
timer.start();
}
private void showImages() {
if (recordIndex == recordSize) {
loadRecords();
recordSize = records.size();
recordIndex = 0;
}
ImageRecord record = records.get(recordIndex);
imageLabel.setIcon(record.getIconForInfoScreen(screenWidth, screenHeight));
recordIndex ;
if (recordIndex < recordSize) {
record = records.get(recordIndex);
int delay = record.getDurationAsInt();
timer.setDelay(delay);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374383.html
上一篇:如何使組件在調整大小時與GridBagLayout布局均勻共享JPanel容器垂直區域?
下一篇:在線繪制具有特定角度度數的字串
