2016-01-18 5 views
1

Я намерен изменить изображения птиц за время, добавив ключевые кадры в цикле for к объекту временной шкалы. Оказывается, отображается только первое изображение. Может ли кто-нибудь указать, в какой части я ошибался. Заранее спасибо.Как изменить изображения с временной шкалой в JavaFX

Кроме того, я заметил, что мне нужно сбросить счетчик «index» на 0 после цикла, иначе он генерирует java.lang.ArrayIndexOutOfBoundsException.

приложение к упаковке;

import javafx.animation.Animation; 
import javafx.animation.KeyFrame; 
import javafx.animation.KeyValue; 
import javafx.animation.Timeline; 
import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.stage.Stage; 
import javafx.util.Duration; 
import javafx.scene.Group; 
import javafx.scene.Node; 
import javafx.scene.Scene; 
import javafx.scene.effect.BoxBlur; 
import javafx.scene.effect.DropShadow; 
import javafx.scene.image.Image; 
import javafx.scene.image.ImageView; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.layout.StackPane; 

public class Main extends Application 

{

int index=0; 
@Override 
public void start(Stage primaryStage) { 
    try { 

     ImageView bgV = new ImageView(); 
     Image img_BG = new Image(Main.class.getResourceAsStream("background.png")); 
     bgV.setImage(img_BG); 
     bgV.setEffect(new BoxBlur()); 
     bgV.setOpacity(0.5); 

     ImageView t1V = new ImageView(); 
     Image img_t1 = new Image(Main.class.getResourceAsStream(
       "t1.png" 
       )); 
     t1V.setImage(img_t1); 

     ImageView t2V = new ImageView(); 
     Image img_t2 = new Image(Main.class.getResourceAsStream(
       "t2.png" 
       )); 
     t2V.setImage(img_t2); 

     ImageView t3V = new ImageView(); 
     Image img_t3 = new Image(Main.class.getResourceAsStream(
       "t3.png" 
       )); 
     t3V.setImage(img_t3); 

     Group foreground = new Group(t1V,t2V,t3V); 

     t1V.setTranslateX(20); 
     t1V.setTranslateY(200); 

     t2V.setTranslateX(300); 
     t2V.setTranslateY(200); 

     t3V.setTranslateX(550); 
     t3V.setTranslateY(200); 
     foreground.setEffect(new DropShadow()); 

     String[] 
       birdFiles = {"b1.png", "b2.png", "b3.png", "b4.png", "b5.png", "b6.png"}; 
     double[] ds = { 300,   600,    900,   1200, 1500, 1800}; 

     ImageView birdV = new ImageView(new Image(Main.class.getResourceAsStream(birdFiles[0]))); 
     Group birds = new Group(birdV); 
     birds.setTranslateX(img_BG.getWidth()-100); 

     Timeline timeline = new Timeline(); 
     timeline.setCycleCount(
       Animation.INDEFINITE 
       ); 


     KeyFrame[] kframs = new KeyFrame[birdFiles.length]; 

     for(index=0; index<birdFiles.length; index++) 
     { 
      EventHandler<ActionEvent> 
       onFishined = new EventHandler<ActionEvent>() 
      { 

       @Override 
       public void handle(ActionEvent arg0) 
       { 
        birds.getChildren().setAll(new ImageView(new Image(Main.class.getResourceAsStream(birdFiles[index])))); 

       } 

      }; 
      Duration duration = Duration.millis(ds[index]); 
      KeyFrame 
       kf = new KeyFrame(duration, onFishined,null,null ); 
      timeline.getKeyFrames().add(kf); 

     }//End for i 
     index = 0; 







     timeline.play(); 





     Group root = new Group(bgV,foreground,birds); 

     Scene scene = new Scene(root,img_BG.getWidth(), img_BG.getHeight()); 
     scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 
} 

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

}

+0

Показать похожие: [Как показывают определенную часть изображения в JavaFX] (http://stackoverflow.com/questions/23440980/how-show-specific-part-of-an-image-in-javafx) и [Создание анимации Sprite с помощью JavaFX] (http://blog.netopyr.com/2012/03/09/creating-a -sprite-animation-with-javafx /) – jewelsea

ответ

1

вы не должны объявить index -поле снаружи. это также вызывает вашу проблему: всякий раз, когда вызывается метод handle, он ссылается на ваше поле: index, которое вы установили в 0 после вашего цикла.

для этого вы можете объявить новое поле final и передать его в обработчик:

for (int index = 0; index < birdFiles.length; index++) { 
    final int birdIndex = index; 
    EventHandler<ActionEvent> onFishined = new EventHandler<ActionEvent>() { 

       @Override 
       public void handle(ActionEvent arg0) { 
        birds.getChildren().setAll(new ImageView(new Image(Main.class.getResourceAsStream(birdFiles[birdIndex])))); 
       } 

      }; 
    ... 
} 
+0

Большое спасибо, KnusperPudding, он действительно решил проблему – user1304846

 Смежные вопросы

  • Нет связанных вопросов^_^