( 显示一个转动的风扇)编写一个程序显示一个转动的风扇,如图15-33c 所示。Pause、Resume和Reverse 按钮用于暂停、继续和反转风扇的转动。
package javaseniorprograme; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.scene.paint.Color; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.shape.Arc; import javafx.scene.shape.ArcType; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; /** * 显示一个转动的风扇 * @author ASUS */ public class Exercise15_28 extends Application{ @Override public void start(Stage stage){ // 创建一个圆 Circle c = new Circle(250,135,125,Color.WHITE); c.setStroke(Color.BLACK); // 创建三个按钮 Button bt1 = new Button("Pause"); Button bt2 = new Button("Resume"); Button bt3 = new Button("Reverse"); // 创建一个HBox HBox hbox = new HBox(); hbox.setAlignment(Pos.CENTER); hbox.setSpacing(20); hbox.getChildren().addAll(bt1,bt2,bt3); // 创建四个Arc Arc[] a = new Arc[4]; for(int i = 0; i < 4; i++){ a[i] = new Arc(250,135,120,120,90*i,30); a[i].setStroke(Color.BLACK); a[i].setFill(Color.BLACK); a[i].setType(ArcType.ROUND); } // 创建时间轴动画,顺时针动画与逆时针动画 Timeline timeline1 = new Timeline(); timeline1.setCycleCount(Timeline.INDEFINITE); Timeline timeline2 = new Timeline(); timeline2.setCycleCount(Timeline.INDEFINITE); Duration duration = Duration.millis(2000); KeyValue[] kv1 = new KeyValue[4]; KeyFrame[] kf1 = new KeyFrame[4]; KeyValue[] kv2 = new KeyValue[4]; KeyFrame[] kf2 = new KeyFrame[4]; for(int j = 0; j < 4; j++){ kv1[j] = new KeyValue(a[j].startAngleProperty(), 360+a[j].getStartAngle()); kf1[j] = new KeyFrame(duration,kv1); timeline1.getKeyFrames().add(kf1[j]); kv2[j] = new KeyValue(a[j].startAngleProperty(), -360+a[j].getStartAngle()); kf2[j] = new KeyFrame(duration,kv2); timeline2.getKeyFrames().add(kf2[j]); } bt2.setOnMouseClicked(e->{ timeline2.pause(); timeline1.play(); }); bt1.setOnMouseClicked(e->{ timeline1.pause(); timeline2.pause(); }); bt3.setOnMouseClicked(e->{ timeline1.pause(); timeline2.play(); }); // 创建一个Pane Pane pa = new Pane(); pa.getChildren().addAll(c,a[0],a[1],a[2],a[3]); // 创建一个BorderPane BorderPane pane = new BorderPane(); pane.setCenter(pa); pane.setBottom(hbox); Scene scene = new Scene(pane,500,320); stage.setTitle("Exercise16_03"); stage.setScene(scene); stage.show(); } /** * * @param args */ public static void main(String[] args){ Application.launch(args); } }