2012-10-23 55 views
1

如何在JavaFX中使用動畫製作旋轉線?如你所知,如果這是在C或C++中完成的,它只是循環,goto(x,y),而不是睡眠。但是,在JavaFX中,我在一個循環中繪製了一條線,但在運行時沒有任何反應。有人能幫助我嗎?JavaFX動畫旋轉線

package javafxapplication1; 

import javafx.stage.Stage; 
import java.util.*; 
import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Ellipse; 
import javafx.scene.shape.EllipseBuilder; 
import javafx.scene.shape.LineTo; 
import javafx.scene.shape.MoveTo; 
import javafx.scene.shape.Path; 
import javafx.stage.Stage; 
import javafx.scene.text.Text; 
import javafx.scene.shape.*; 

public class JavaFXApplication1 extends Application { 

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

    public class Canvas 
    { 
    private int width; 
    private int height; 
    private int stride; 
    private byte[] im; 
    private com.sun.prism.Image pimage; 

    public Canvas(int width, int height) 
    { 
     this.width = width; 
     this.height = height; 
     this.stride = width*3; 
     im = new byte[stride*height]; 
    } 
} 


    @Override 
    public void start(Stage primaryStage) { 
     Group root = new Group(); 
     Scene scene = new Scene(root, 800, 600, Color.WHITE); 

    Ellipse lingkaran = EllipseBuilder.create() 
    .centerX(400) 
    .centerY(300) 
    .radiusX(210) 
    .radiusY(210) 
    .strokeWidth(3) 
    .build(); 

    Path path = new Path();  

    MoveTo moveTo = new MoveTo(); 
    moveTo.setX(400); 
    moveTo.setY(300); 

    LineTo lineTo = new LineTo(); 
    lineTo.setX(400); 
    lineTo.setY(100); 

    path.getElements().add(moveTo); 
    path.getElements().add(lineTo); 
    path.setStrokeWidth(3); 
    path.setStroke(Color.BLACK); 

    int x1 = 400; 
    int y1 = 300; 
    int x2 = 400; 
    int y2 = 100; 
    double rr = 0; 
    double dx, temp1; 
    double dy, temp2; 

    temp1 = x2; 
    temp2 = y2; 
    //root.getChildren().add(lingkaran); 

    for(int i = 0; i < 500; i++){    
     Line line = new Line(); 
     Ellipse ellipse = new Ellipse(); 

     ellipse.setCenterX(400); 
     ellipse.setCenterY(300); 
     ellipse.setRadiusX(210); 
     ellipse.setRadiusY(210); 
     ellipse.setStroke(Color.BLACK); 
     ellipse.setFill(Color.WHITE); 

     line.setStartX(x1); 
     line.setStartY(y1);   

     line.setStroke(Color.RED);   

     dx = ((x2-x1)*Math.cos(rr)) - ((y2-y1)*Math.sin(rr)) +x1; 
     dy = ((x2-x1)*Math.sin(rr)) + ((y2-y1)*Math.cos(rr)) +y1; 

     temp1 = dx; 
     temp2 = dy; 

     line.setEndX(dx); 
     line.setEndY(dy); 

     rr = rr + 0.05; 

     root.getChildren().add(ellipse); 

     root.getChildren().add(line); 
    }  

    primaryStage.setScene(scene); 
    primaryStage.show(); 


    } 
} 

回答

1

改爲使用帶有KeyFrame的RotateTransition或動畫時間軸。

請參閱How to draw a clock with JavaFX 2?瞭解使用JavaFX旋轉線條的指令和示例代碼。

您的代碼不起作用,因爲您必須將控制權交還給JavaFX系統,以便它可以執行實際呈現。此外,直接在代碼中引用com.sun類是不明智的,因爲這些類可能會在將來的JavaFX版本中更改API,從而影響代碼的兼容性。