Source of ShowPolygon.java


  1: 
  2: import javafx.application.Application;
  3: import javafx.collections.ObservableList;
  4: import javafx.scene.Scene;
  5: import javafx.scene.layout.Pane;
  6: import javafx.scene.paint.Color;
  7: import javafx.stage.Stage;
  8: import javafx.scene.shape.Polygon;
  9: 
 10: public class ShowPolygon extends Application {
 11:   @Override // Override the start method in the Application class
 12:   public void start(Stage primaryStage) {
 13:     // Create a scene and place it in the stage
 14:     Scene scene = new Scene(new MyPolygon(), 400, 400);
 15:     primaryStage.setTitle("ShowPolygon"); // Set the stage title
 16:     primaryStage.setScene(scene); // Place the scene in the stage
 17:     primaryStage.show(); // Display the stage
 18:   }
 19: 
 20:   /**
 21:    * The main method is only needed for the IDE with limited
 22:    * JavaFX support. Not needed for running from the command line.
 23:    */
 24:   public static void main(String[] args) {
 25:     launch(args);
 26:   }
 27: }
 28: 
 29: class MyPolygon extends Pane {
 30:   private void paint() {
 31:     // Create a polygon and place polygon to pane
 32:     Polygon polygon = new Polygon();
 33:     polygon.setFill(Color.WHITE);
 34:     polygon.setStroke(Color.BLACK);
 35:     ObservableList<Double> list = polygon.getPoints();
 36: 
 37:     double centerX = getWidth() / 2, centerY = getHeight() / 2;
 38:     double radius = Math.min(getWidth(), getHeight()) * 0.4;
 39: 
 40:     // Add points to the polygon list
 41:     for (int i = 0; i < 6; i++) {
 42:       list.add(centerX + radius * Math.cos(2 * i * Math.PI / 6));
 43:       list.add(centerY - radius * Math.sin(2 * i * Math.PI / 6));
 44:     }
 45: 
 46:     getChildren().clear();
 47:     getChildren().add(polygon);
 48:   }
 49: 
 50:   @Override
 51:   public void setWidth(double width) {
 52:     super.setWidth(width);
 53:     paint();
 54:   }
 55: 
 56:   @Override
 57:   public void setHeight(double height) {
 58:     super.setHeight(height);
 59:     paint();
 60:   }
 61: }