![]() | Session 7 | ![]() |
First graphic program
Let's start with a new class called BlackSquare: File -> New -> JavaFXApplication. Here is the code:
import javafx.application.Application;
import javafx.stage.Stage;
public class BlackSquare extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
}
}
Every JavaFX program has to be defined in a class that extends javafx.application.Application. The program starts its work from the main method, as usually.
launchmethod (line 7) is a static method defined inApplicationclass for launching a stand-alone JavaFX application.- The main class overrides
startmethod defined inApplicationclass (line 11). The method's argument is an object ofStagetype. AStagetype object (called primary stage) is a window which is automatically created by the JVM when the application is launched.
Supplement start method with some content.
public void start(Stage primaryStage) {
Group root = new Group(); // create a root node
Rectangle rectangle1 = new Rectangle(50, 50, 435, 435);
root.getChildren().add(rectangle1); // place the rectangle onto the scene
Scene scene1 = new Scene(root, 535, 535, Color.SNOW); // create the scene
primaryStage.setTitle("Black square"); // set a title for the stage
primaryStage.setScene(scene1); // place the scene onto the stage
primaryStage.show(); // display the stage
}
The method start normally places shapes and UI controls on the scene, and also displays the scene on the stage, as shown below:

Line 2 creates a Group type object that acts as a root. A Rectangle type object is a shape that we would like to see. Line 4 places the rectangle into a Scene type object. The Scene type object is created using the constructor Scene(root, width, height, color). This constructor specifies the color, width and height of the scene and places the root on the scene. Finally, we place the scene onto the stage (Line 7).
JavaFX names Stage and Scene classes using an analogy with the theatre. We can assume that the stage is a platform which supports scenes, and in each scene there are actors(shapes) who perform in the scenes.
PS! Pay attention:
JavaFX applications often require some extra classes which has to be imported. In this case, the IDE can provide the ability to choose between several classes with the same name (Alt + Enter). The right choice should contain the javafx package name (e.g. import javafx.scene.shape.Rectangle; in order to draw a rectangle).
Try out
Try to run the program given above.
Similar images were also made a hundred years ago: https://www.wikiart.org/en/kazimir-malevich/black-square-1915
![]() | Session 7 | ![]() |

