2016-03-08 99 views
0

進入堆棧後,是否可以將我的元素進行洗牌? SO,計劃是每次顯示隨機圖像。 我下面的代碼:隨機播放元素

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package imagedisplay; 

import javafx.animation.KeyFrame; 
import javafx.animation.KeyValue; 
import javafx.animation.Timeline; 
import javafx.application.Application; 
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; 
/** 
* 
* @author D 
*/ 
public class ImageDisplay extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Image Img1 = new Image("file:lib/1.jpg"); 
     Image Img2 = new Image("file:lib/2.jpg"); 
     Image Img3 = new Image("file:lib/3.jpg"); 
     Image Img4 = new Image("file:lib/4.jpg"); 
     ImageView ViewImg = new ImageView(); 
     Timeline tl = new Timeline(

       new KeyFrame(Duration.seconds(25), new KeyValue(ViewImg.imageProperty(), Img1)), 
       new KeyFrame(Duration.seconds(20), new KeyValue(ViewImg.imageProperty(), Img2)), 
       new KeyFrame(Duration.seconds(15), new KeyValue(ViewImg.imageProperty(), Img3)), 
       new KeyFrame(Duration.seconds(10), new KeyValue(ViewImg.imageProperty(), Img4)), 
       new KeyFrame(Duration.seconds(5), new KeyValue(ViewImg.imageProperty(), null))); 
     tl.play(); 
     StackPane st = new StackPane(); 
     st.getChildren().add(ViewImg); 
     primaryStage.setScene(new Scene(st, 800, 600)); 
     primaryStage.show(); 
    } 

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

基本上這個代碼是什麼,它會顯示一些圖像逐一爲每5秒。我想要展示他們,但要冷靜。

+1

它們添加到列表'',然後執行'Collections.shuffle(名單)',和** **然後把它們在'Timeline'? –

回答

-1

集合類具有內置的洗牌方法。

Timeline tl = new Timeline(
    Collections.shuffle(Arrays.asList(
      new KeyFrame(Duration.seconds(25), new KeyValue(ViewImg.imageProperty(), Img1)), 
      new KeyFrame(Duration.seconds(20), new KeyValue(ViewImg.imageProperty(), Img2)), 
      new KeyFrame(Duration.seconds(15), new KeyValue(ViewImg.imageProperty(), Img3)), 
      new KeyFrame(Duration.seconds(10), new KeyValue(ViewImg.imageProperty(), Img4)), 
      new KeyFrame(Duration.seconds(5), new KeyValue(ViewImg.imageProperty(), null))))); 
+0

感謝您糾正安迪! – PyThon

+0

謝謝,但這種方法不會返回任何東西,這就是爲什麼即時通訊使用它的錯誤。 – dailyadd

+0

如果你嘗試這個PyThon,你可能會發現它不會做你認爲它會做的事。例如,Img4,將在持續10秒後始終顯示。這是因爲您正在洗牌關鍵幀,時間軸將在內部按持續時間排序。可能你想要做的是把圖像放在一個數組中,然後在創建基於數組的關鍵幀之前對數組進行洗牌。 – jewelsea