*15.23 (自动改变大小的停止标识)
重写编程练习题14.15, 当窗体改变大小的时候,停止标识的宽度和髙度自动改变大小
- 习题思路
- 新建一个Polygon()绘出八边形,new一个Label表示文字STOP
- 新建一个方法,被调用时重新绘制八边形,并重新设置文字位置
- 监听Scene,当大小改变时,调用第二步新建的方法
代码示例:编程练习题15_23AutoChangeSizeStop.java
package chapter_15;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class 编程练习题15_23AutoChangeSizeStop extends Application{
Polygon polygon = new Polygon();
Label text = new Label("STOP");
@Override
public void start(Stage primaryStage) throws Exception {
Pane pane = new StackPane();
pane.getChildren().add(polygon);
polygon.setFill(Color.RED);
//polygon.setStroke(Color.BLACK);
ObservableList<Double> list = polygon.getPoints();
final double WIDTH = 200, HEIGHT = 200;
double centerX = WIDTH / 2, centerY = HEIGHT / 2;
double radius = Math.min(WIDTH, HEIGHT)*0.4;
for(int i = 0;i < 8;i++) {
list.add(centerX + radius * Math.cos(34.95+2 * i* Math.PI / 8));
list.add(centerY -radius * Math.sin(34.95+2 * i * Math.PI / 8));
}
text.setTextFill(Color.WHITE);
text.setFont(Font.font("Times New Roman", FontWeight.BOLD, 30));
pane.getChildren().add(text);
Scene scene = new Scene(pane, WIDTH, HEIGHT);
scene.widthProperty().addListener((observable, oldValue, newValue) -> resizeComponents(newValue.doubleValue(), scene.getHeight()));
scene.heightProperty().addListener((observable, oldValue, newValue) -> resizeComponents(scene.getWidth(), newValue.doubleValue()));
primaryStage.setTitle("编程练习题15_23AutoChangeSizeStop");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
private void resizeComponents(double width, double height) {
double centerX = width / 2;
double centerY = height / 2;
double radius = Math.min(width, height) * 0.4;
// Update polygon points
ObservableList<Double> points = polygon.getPoints();
points.clear();
for (int i = 0; i < 8; i++) {
points.add(centerX + radius * Math.cos(34.95+2 * i* Math.PI / 8));
points.add(centerY -radius * Math.sin(34.95+2 * i * Math.PI / 8));
}
// Update label properties
double fontSize = radius / 3; // Adjust font size based on radius
text.setLayoutX(centerX - text.getLayoutBounds().getWidth() / 2);
text.setLayoutY(centerY + text.getLayoutBounds().getHeight() / 2);
text.setFont(Font.font("Times New Roman", FontWeight.BOLD, fontSize));
}
}
- 结果展示