如何在JavaFX中制作带动画的旋转线?如你所知,如果这是在C或C ++中完成的,它只是循环,goto(x,y),而不是sleep。但是,在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();
}
}
答案 0 :(得分:1)
使用RotateTransition或动画时间轴代替KeyFrame。
有关使用JavaFX旋转一行的说明和示例代码,请参阅How to draw a clock with JavaFX 2?。
您的代码不起作用,因为您必须将控制权交还给JavaFX系统,以便它可以执行实际渲染。此外,不建议直接引用代码中的com.sun类,因为这些类可能会在将来的JavaFX版本中更改API,从而损害代码的兼容性。