2
我寫了一個javafx對象「Ball」來創建一個Sphere。我現在試圖讓對象出現在我的主類中。 理想情況下,我會使用一個關鍵偵聽器來創建/銷燬球。但我甚至無法讓球出現在屏幕上,甚至無法讓我的1500x900屏幕出現。如何顯示javafx 3D對象?
這裏我爲球代碼:
// ball object
package bouncingballs;
import javafx.animation.Interpolator;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.scene.layout.Pane;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Sphere;
import javafx.util.Duration;
import static javafx.util.Duration.seconds;
public class Ball extends Pane {
//Create 3D ball
private Sphere ball;
private Double radius;
private PhongMaterial color;
private Polygon poly;
private PathTransition path;
private Integer speed;
//Create path and animate ball in constructor
public Ball(Double radius, PhongMaterial color, Polygon poly) {
this.radius = radius;
this.color = color;
ball.setRadius(radius);
ball.setMaterial(color);
this.poly = poly;
speed = 10;
path.setPath(poly);
path.setNode(ball);
path.setInterpolator(Interpolator.LINEAR);
path.setDuration(Duration.seconds(speed));
path.setCycleCount(Timeline.INDEFINITE);
path.play();
}
//some test accessors/mutators
public void setRadius(Double radius) {
this.radius = radius;
}
public Double getRadius() {
return radius;
}
}
這是我爲我的主類的代碼,它應該創建球對象,並顯示它們的動畫。動畫應該遵循Polygon對象poly來模擬彈跳球。
//main object to show Balls to screen
package bouncingballs;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
public class BouncingBalls extends Application {
@Override
public void start(Stage primaryStage) {
//create path to simulate bouncing ball
Polygon poly = new Polygon(750, 850, 50, 675, 500, 50, 750, 850, 1000, 50, 1450, 675);//creates path to simulate bouncing ball on 1500x900 screen
Double radius = 50.0;
PhongMaterial color = new PhongMaterial();
color.setDiffuseColor(Color.OLIVE);
Ball ball = new Ball(radius, color, poly);
StackPane root = new StackPane();
root.getChildren().add(ball);
Scene scene = new Scene(root, 1500, 900);
primaryStage.setTitle("Bouncing Balls");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{launch(args);
}
}