2017-03-07 186 views
0

如何延迟绘制形状? 例如,在开始时绘制几个矩形,1秒钟后绘制fillOval,3秒后绘制另一个椭圆形等等。JavaFX延迟绘制形状

+0

我会去了解一下睡眠命令,它做什么它挂起主线程(运行整个程序因此线程),然而对于许多秒钟你告诉它。所以你可以画一些东西,等待几秒钟,画另一件事。否则,它将需要线程。 – SomeStudent

+1

@SomeStudent您无法在FX应用程序线程上调用sleep()。它会阻止呈现UI。 –

+0

我明白了,我的b,并不确定,没有永远做fx。 AH,对,现在我记得,你可以使用FadeTransition ft = new FadeTransition(Duration.millis(1000),night);该代码来自我的旧fx应用程序。这里的夜晚是我场景的一个物体,它在黑白之间交替(如此白天和黑夜)。 – SomeStudent

回答

2

您正在描述动画。为此,您应该使用Animation API

例如,使用Timeline

import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 

import javafx.animation.KeyFrame; 
import javafx.animation.Timeline; 
import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.layout.Pane; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Ellipse; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 
import javafx.util.Duration; 

public class ShapeAnimationExample extends Application { 

    private final Random rng = new Random(); 


    @Override 
    public void start(Stage primaryStage) { 


     List<Rectangle> fewRectangles = new ArrayList<>(); 
     for (int i = 0 ; i < 5 ; i++) { 
      Rectangle r = new Rectangle(rng.nextInt(300)+50, rng.nextInt(300)+50, rng.nextInt(100)+50, rng.nextInt(100)+50); 
      r.setFill(randomColor()); 
      fewRectangles.add(r); 
     } 

     List<Ellipse> ovals = new ArrayList<>(); 
     for (int i = 0 ; i < 5 ; i++) { 
      Ellipse e = new Ellipse(rng.nextInt(400)+50, rng.nextInt(400)+50, rng.nextInt(50)+50, rng.nextInt(50)+50); 
      e.setFill(randomColor()); 
      ovals.add(e); 
     } 

     Pane pane = new Pane(); 
     pane.setMinSize(600, 600); 

     Timeline timeline = new Timeline(); 
     Duration timepoint = Duration.ZERO ; 
     Duration pause = Duration.seconds(1); 

     KeyFrame initial = new KeyFrame(timepoint, e -> pane.getChildren().addAll(fewRectangles)); 
     timeline.getKeyFrames().add(initial); 

     for (Ellipse oval : ovals) { 
      timepoint = timepoint.add(pause); 
      KeyFrame keyFrame = new KeyFrame(timepoint, e -> pane.getChildren().add(oval)); 
      timeline.getKeyFrames().add(keyFrame); 
     } 

     Scene scene = new Scene(pane); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 

     timeline.play(); 
    } 

    private Color randomColor() { 
     return new Color(rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), 1.0); 
    } 

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

谢谢你,这是我一直在寻找的 –