1+ package ch_15 ;
2+ 3+ import javafx .application .Application ;
4+ import javafx .collections .ObservableList ;
5+ import javafx .scene .Scene ;
6+ import javafx .scene .layout .StackPane ;
7+ import javafx .scene .paint .Color ;
8+ import javafx .scene .shape .Polygon ;
9+ import javafx .scene .text .Font ;
10+ import javafx .scene .text .Text ;
11+ import javafx .scene .text .TextAlignment ;
12+ import javafx .stage .Stage ;
13+ 14+ /**
15+ * *15.23 (Auto resize stop sign) Rewrite Programming Exercise 14.15 so that the stop
16+ * sign’s width and height are automatically resized when the window is resized.
17+ */
18+ public class Exercise15_23 extends Application {
19+ double originalWidth = 200 , originalHeight = 200 ;
20+ double originalFontSize = 42 ;
21+ @ Override
22+ public void start (Stage primaryStage ) throws Exception {
23+ StackPane stackPane = new StackPane ();
24+ stackPane .setPrefWidth (originalWidth );
25+ stackPane .setPrefHeight (originalHeight );
26+ drawStopSign (stackPane );
27+ Scene scene = new Scene (stackPane , originalWidth , originalHeight );
28+ primaryStage .setScene (scene );
29+ primaryStage .setTitle (getClass ().getName ());
30+ primaryStage .setResizable (true );
31+ primaryStage .show ();
32+ 33+ scene .widthProperty ().addListener ((observable , oldValue , newValue ) -> {
34+ stackPane .setPrefWidth ((double ) newValue );
35+ drawStopSign (stackPane );
36+ 37+ });
38+ 39+ scene .heightProperty ().addListener ((observable , oldValue , newValue ) -> {
40+ stackPane .setPrefHeight ((double ) newValue );
41+ drawStopSign (stackPane );
42+ });
43+ }
44+ 45+ void drawStopSign (StackPane stackPane ) {
46+ Polygon polygon = new Polygon ();
47+ stackPane .getChildren ().clear ();
48+ double width = stackPane .getPrefWidth ();
49+ double height = stackPane .getPrefHeight ();
50+ stackPane .getChildren ().add (polygon );
51+ polygon .setFill (Color .RED );
52+ polygon .setStroke (Color .RED );
53+ 54+ ObservableList <Double > list = polygon .getPoints ();
55+ double centerX = width / 2 , centerY = height / 2 ;
56+ double radius = Math .min (width , height ) * 0.4 ;
57+ // Add points to the polygon list -> divide Math.PI by 8 for Octagon
58+ for (int i = 0 ; i < 8 ; i ++) {
59+ list .add (centerX + radius * Math .cos (2 * i * Math .PI / 8 ));
60+ list .add (centerY - radius * Math .sin (2 * i * Math .PI / 8 ));
61+ }
62+ polygon .setRotate (22.5 );
63+ 64+ Text text = new Text ("STOP" );
65+ text .setTextAlignment (TextAlignment .CENTER );
66+ text .setFill (Color .WHITE );
67+ text .setStroke (Color .WHITE );
68+ text .setFont (Font .font (originalFontSize * Math .min (width , height ) / Math .min (originalWidth , originalHeight )));
69+ stackPane .getChildren ().add (text );
70+ 71+ }
72+ 73+ }
0 commit comments