Java黑皮书15.28(显示一个运转的风扇)
package sample;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
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.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
FanPane fanPane = new FanPane();
HBox hBox = new HBox(5);
Button button_Pause = new Button("Pause");
Button button_Resume = new Button("Resume");
Button button_Reverse = new Button("Reverse");
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(button_Pause, button_Resume, button_Reverse);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(fanPane);
borderPane.setBottom(hBox);
Scene scene = new Scene(borderPane, 600, 600);
primaryStage.setTitle("显示一个运转的风扇");
primaryStage.setScene(scene);
primaryStage.show();
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(20), e -> fanPane.move()));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
scene.widthProperty().addListener(e -> fanPane.setW(fanPane.getWidth()));
scene.heightProperty().addListener(e -> fanPane.setH(fanPane.getHeight()));
button_Pause.setOnAction(e -> timeline.pause());
button_Resume.setOnAction(e -> timeline.play());
button_Reverse.setOnAction(e -> fanPane.reverse());
}
public static void main(String[] args) {
launch(args);
}
}
class FanPane extends Pane {
private double width = 600;
private double high = 600;
private double radius = Math.min(width, high) * 0.5;
private double increment = 5;
private Arc arc[] = new Arc[4];
private double startAngle = 10;
private Circle circle = new Circle(width / 2, high / 2, radius);
public FanPane() {
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
getChildren().add(circle);
for (int i = 0; i < 4; i++) {
arc[i] = new Arc(width / 2, high / 2, radius * 0.9, radius * 0.9, startAngle + i * 90, 35);
arc[i].setFill(Color.BLACK);
arc[i].setType(ArcType.ROUND);
getChildren().addAll(arc[i]);
}
}
public void reverse() { increment *= -1; }
public void move() { setStartAngle(startAngle + increment); }
public void setStartAngle(double angle) { startAngle = angle;setValues(); }
public void setValues() {
radius = Math.min(width, high) * 0.5;
circle.setRadius(radius);
circle.setCenterX(width / 2);
circle.setCenterY(high / 2);
for (int i = 0; i < 4; i++) {
arc[i].setRadiusX(radius * 0.9);
arc[i].setRadiusY(radius * 0.9);
arc[i].setCenterX(width / 2);
arc[i].setCenterY(high / 2);
arc[i].setStartAngle(startAngle + i * 90);
}
}
public void setW(double w) { this.width = w;setValues(); }
public void setH(double h) { this.high = h;setValues(); }
}
运行结果