|
| 1 | +package ch_15; |
| 2 | + |
| 3 | +import javafx.application.Application; |
| 4 | +import javafx.scene.Scene; |
| 5 | +import javafx.scene.layout.Pane; |
| 6 | +import javafx.scene.paint.Color; |
| 7 | +import javafx.scene.shape.Polygon; |
| 8 | +import javafx.scene.shape.Rectangle; |
| 9 | +import javafx.scene.text.Text; |
| 10 | +import javafx.stage.Stage; |
| 11 | + |
| 12 | +/** |
| 13 | + * *15.14 (Geometry: inside a polygon?) Write a program that draws a fixed polygon |
| 14 | + * with points at (40, 20), (70, 40), (60, 80), (45, 45), and (20, 60). Whenever the mouse is moved, display a message indicating whether the mouse |
| 15 | + * point is inside the polygon at the mouse point or outside of it, as shown in |
| 16 | + * Figure 15.27c. To detect whether a point is inside a polygon, use the contains |
| 17 | + * method defined in the Node class. |
| 18 | + */ |
| 19 | +public class Exercise15_14 extends Application { |
| 20 | + static final double WIDTH = 400; |
| 21 | + static final double HEIGHT = 150; |
| 22 | + static double mouseX; |
| 23 | + static double mouseY; |
| 24 | + |
| 25 | + @Override |
| 26 | + public void start(Stage primaryStage) throws Exception { |
| 27 | + Pane pane = new Pane(); |
| 28 | + Polygon polygon = new Polygon(40, 20, 70, 40, 60, 80, 45, 45, 20, 60); |
| 29 | + polygon.setFill(Color.TRANSPARENT); |
| 30 | + polygon.setStroke(Color.BLACK); |
| 31 | + |
| 32 | + |
| 33 | + Text message = new Text(polygon.getStrokeWidth() / 2, polygon.getStrokeWidth() / 2, ""); |
| 34 | + pane.getChildren().add(polygon); |
| 35 | + pane.getChildren().add(message); |
| 36 | + Scene scene = new Scene(pane, WIDTH, HEIGHT); |
| 37 | + |
| 38 | + scene.setOnMouseMoved(mouseEvent -> { |
| 39 | + mouseX = mouseEvent.getSceneX(); |
| 40 | + mouseY = mouseEvent.getSceneY(); |
| 41 | + if (isPointInPolygon(mouseX, mouseY, polygon)) { |
| 42 | + message.setText("Mouse point is inside the polygon"); |
| 43 | + } else { |
| 44 | + message.setText("Mouse point is outside the polygon"); |
| 45 | + } |
| 46 | + message.setX(mouseX); |
| 47 | + message.setY(mouseY); |
| 48 | + }); |
| 49 | + |
| 50 | + primaryStage.setTitle(getClass().getName()); |
| 51 | + primaryStage.setScene(scene); |
| 52 | + primaryStage.show(); |
| 53 | + } |
| 54 | + |
| 55 | + private boolean isPointInPolygon(double mouseX, double mouseY, Polygon polygon) { |
| 56 | + return polygon.contains(mouseX, mouseY); |
| 57 | + } |
| 58 | + |
| 59 | + public static void main(String[] args) { |
| 60 | + launch(args); |
| 61 | + } |
| 62 | +} |
0 commit comments