Source of FrenchFlagApplication.java


  1: import javafx.application.Application;
  2: import javafx.stage.Stage;
  3: import javafx.scene.Scene;
  4: import javafx.scene.layout.Pane;
  5: import javafx.scene.canvas.Canvas;
  6: import javafx.scene.canvas.GraphicsContext;
  7: import javafx.scene.paint.Color;

  9: /**
 10:  * A JavaFX Application to draw the French flag.
 11:  *
 12:  * @author Mark Young (A00000000)
 13:  */
 14: public class FrenchFlagApplication extends Application {

 16:     @Override
 17:     public void start(Stage applicationStage) {
 18:         Pane pane = makePane();
 19:         Scene scene = new Scene(pane);          // A scene containing the pane
 20:         applicationStage.setTitle("French Flag");   // Set window's title
 21:         applicationStage.setScene(scene);           // Set window's scene
 22:         applicationStage.show();                    // Display window
 23:     }

 25:     /**
 26:      * Create a Pane containing a picture of the French flag.
 27:      *
 28:      * @return new Pane with flag image
 29:      */
 30:     private Pane makePane() {
 31:         Pane pane = new Pane();                 // An empty pane    
 32:         Canvas canvas = makeFlag();
 33:         
 34:         // put it all together, give it a title, and show it
 35:         pane.getChildren().add(canvas);             // Add canvas to pane 
 36:         return pane;
 37:     }

 39:     // flag drawing constants
 40:     private static final int WIDTH = 900;
 41:     private static final int HEIGHT = WIDTH * 2 / 3;

 43:     private static final int[] PROPORTIONS = {30, 33, 37};

 45:     /**
 46:      * Create a picture of the French flag.
 47:      *
 48:      * @return a new Canvas with flag image
 49:      */
 50:     private Canvas makeFlag() {
 51:         Canvas result = new Canvas(WIDTH, HEIGHT);  // A canvas to draw on
 52:         double totalWidth, blueWidth, redLeft, redWidth;
 53:         GraphicsContext drawing = result.getGraphicsContext2D();
 54:         Color blue = Color.rgb(0, 85, 164);
 55:         Color red = Color.rgb(239, 65, 53);
 56:         
 57:         // calculate the edges of the blue and red stripes
 58:         totalWidth = PROPORTIONS[0] + PROPORTIONS[1] + PROPORTIONS[2];
 59:         blueWidth = (double) PROPORTIONS[0] / totalWidth;
 60:         redWidth = (double) PROPORTIONS[2] / totalWidth;
 61:         redLeft = 1 - redWidth;

 63:         // draw left stripe -- blue
 64:         drawing.setFill(blue);
 65:         drawing.fillRect(0, 0, WIDTH * blueWidth, HEIGHT);
 66:         
 67:         // draw right stripe -- red
 68:         drawing.setFill(red);
 69:         drawing.fillRect(WIDTH * redLeft, 0, WIDTH * redWidth, HEIGHT);
 70:         
 71:         return result;
 72:     }

 74:     public static void main(String[] args) {
 75:         launch(args); // Launch application
 76:     }
 77: }