Drawing Squares and Circles in JavaFX in Pure Java

I already gave an example of how to draw Squares and Circles on an FXML-generatated UI. Sometimes, you want to work without taking the time to create an FXML document. So this example delves into doing the same thing without using FXML.

Just drawing squares isn’t extremely exciting, because, … let’s face it, … the only time you want a window with one square and one circle in it, is when you are implementing the Candy Land board game.

Classic Candy Land Board Game
The only time you need just a circle and a square in a window, is when you are implementing a Candy Land game.
By Source (WP:NFCC#4), Fair use, https://en.wikipedia.org/w/index.php?curid=46225642

Note: For anyone new to JavaFX in general, be sure to read through my introduction to JavaFX, first.

So let’s get on with it.

package com.whatisjavafx;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
  @Override
  public void start(Stage stage) {
    
    //creating a Group as our root node
    Group root = new Group();
    
    //configuring a Canvas to draw on
    Canvas canvas = new Canvas();
    canvas.setWidth(600);
    canvas.setHeight(400);
    
    //drawing on the Canvas
    GraphicsContext gc = 
        canvas.getGraphicsContext2D();
    draw( gc );
    
    //adding the Canvas to the scene graph
    root.getChildren().add(canvas);

    //adding the root to the scene
    Scene scene = new Scene(root);
    
    //adding the scene to the stage
    //and showing the stage/window
    stage.setScene(scene);
    stage.setTitle("Circles and Squares");
    stage.show();
  }
  
  /**
   * Drawing the shapes
   */
  private void draw(GraphicsContext gc) {
    gc.setFill(Color.GREEN);
    gc.fillOval(50, 100, 200, 200);
    gc.setFill(Color.RED);
    gc.fillRect(300, 100, 200, 200);
  }

  public static void main(String[] args) {
    launch(args);
  }
}

 

I’ve placed all the code into one class, because there just isn’t enough to justify separating it out into multiple classes.

I’ve commented what all the code does, but for those that don’t like reading comments–you know who you are–I’ll explain the code.

First glance at the imports. Notice that they are all using javafx packages. Several of the classes common in JavaFX have counterparts (or evil twins, depending on your view point) in the AWT and Swing API’s. Use the JavaFX version when in doubt as to which version to use.

The class Main extends Application. All JavaFX applications are javafx.application.Application‘s. Applications have a call to launch(), usually in the main() method. The launch() method eventually calls the start() method that actually starts JavaFX applicaitons, and provides a stage, … probably because, all the app’s a Stage. (Yes, I went there.)

The goal of the JavaFX coder is to fill the Stage with cool, useful stuff. In this case, we start with a Group. Groups make good roots when drawing, but it’s nice to put a Canvas in the Group to do the drawing on. So that’s what we do.

Don’t worry too much about the whole root.getChildren().add(canvas); thing. That’s just how you add children to roots. You’ll want to memorize that one, ’cause you’ll be baffled why your code isn’t working otherwise.

Once your root has a Canvas, add your root to your scene and your scene to your stage. That completes your setup of the “Scene Graph.” The scene graph is just a node tree containing all your UI elements.

But what about that GraphicsContext thingy?

You thought I forgot, didn’t you.

The GraphicsContext is where all the drawing magic happens. You need your Canvas’s GraphicContext in order to draw on it. Calling the getGraphicsContext2D() method gets you a copy of the all important GraphicsContext.

We pass the GraphicsContext to the draw() method, because we might want to change the drawing later to something more exciting than a circle and a square, and we don’t want to disturb that precious start() method that we barely got working.

The GraphicsContext has lots and lots of cool and possibly confusing drawing methods. We’ll stick with setFillColor(), fillOval() and fillRect().

setFillColor() sets your drawing color that you fill shapes with to the javafx.scene.paint.Color of your choosing. The pre-defined colors you can choose from are, well, the list is long.

ALICEBLUE

ANTIQUEWHITE

AQUA

AQUAMARINE

AZURE

BEIGE

BISQUE

BLACK

BLANCHEDALMOND

BLUE

BLUEVIOLET

BROWN

BURLYWOOD

CADETBLUE

CHARTREUSE

CHOCOLATE

CORAL

CORNFLOWERBLUE

CORNSILK

CRIMSON

CYAN

DARKBLUE

DARKCYAN

DARKGOLDENROD

DARKGRAY

DARKGREEN

DARKGREY

DARKKHAKI

DARKMAGENTA

DARKOLIVEGREEN

DARKORANGE

DARKORCHID

DARKRED

DARKSALMON

DARKSEAGREEN

DARKSLATEBLUE

DARKSLATEGRAY

DARKSLATEGREY

DARKTURQUOISE

DARKVIOLET

DEEPPINK

DEEPSKYBLUE

DIMGRAY

DIMGREY

DODGERBLUE

FIREBRICK

FLORALWHITE

FORESTGREEN

FUCHSIA

GAINSBORO

GHOSTWHITE

GOLD

GOLDENROD

GRAY

GREEN

GREENYELLOW

GREY

HONEYDEW

HOTPINK

INDIANRED

INDIGO

IVORY

KHAKI

LAVENDER

LAVENDERBLUSH

LAWNGREEN

LEMONCHIFFON

LIGHTBLUE

LIGHTCORAL

LIGHTCYAN

LIGHTGOLDENRODYELLOW

LIGHTGRAY

LIGHTGREEN

LIGHTGREY

LIGHTPINK

LIGHTSALMON

LIGHTSEAGREEN

LIGHTSKYBLUE

LIGHTSLATEGRAY

LIGHTSLATEGREY

LIGHTSTEELBLUE

LIGHTYELLOW

LIME

LIMEGREEN

LINEN

MAGENTA

MAROON

MEDIUMAQUAMARINE

MEDIUMBLUE

MEDIUMORCHID

MEDIUMPURPLE

MEDIUMSEAGREEN

MEDIUMSLATEBLUE

MEDIUMSPRINGGREEN

MEDIUMTURQUOISE

MEDIUMVIOLETRED

MIDNIGHTBLUE

MINTCREAM

MISTYROSE

MOCCASIN

NAVAJOWHITE

NAVY

OLDLACE

OLIVE

OLIVEDRAB

ORANGE

ORANGERED

ORCHID

PALEGOLDENROD

PALEGREEN

PALETURQUOISE

PALEVIOLETRED

PAPAYAWHIP

PEACHPUFF

PERU

PINK

PLUM

POWDERBLUE

PURPLE

RED

ROSYBROWN

ROYALBLUE

SADDLEBROWN

SALMON

SANDYBROWN

SEAGREEN

SEASHELL

SIENNA

SILVER

SKYBLUE

SLATEBLUE

SLATEGRAY

SLATEGREY

SNOW

SPRINGGREEN

STEELBLUE

TAN

TEAL

THISTLE

TOMATO

TRANSPARENT (Yeah, … Couldn’t make that one the right color.)

TURQUOISE

VIOLET

WHEAT

WHITE (I’ll leave that color to your imagination.)

WHITESMOKE

YELLOW

YELLOWGREEN

Of course you can define your own colors with the Color constructor.

Color(double red, double green, double blue, double opacity)

But, where’s the fun in that.

The fillOval() method, … SURPRISE! … fills an oval with your fill color. The oval is defined as fillOval(x, y, width, height), all in pixels. The upper left hand corner is (0,0).

The fillRect() method fills a shape that just happens to be a rectangle.

There you have it, … how to draw circles and rectangles using absolutely no FXML.

Leave a Reply

Your email address will not be published. Required fields are marked *