( 顯示一個轉動的風扇)編寫一個程序顯示一個轉動的風扇,如圖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); } }