2016-03-08 98 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