Session 7 |
First graphic program
Let's start with a new class called BlackBox: File -> New -> JavaFXApplication. Here is the code:
import javafx.application.Application; import javafx.stage.Stage; public class BlackBox extends Application { @Override public void start(Stage primaryStage) { } public static void main(String[] args) { launch(args); } }
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.
launch
method (line 12) is a static method defined inApplication
class for launching a stand-alone JavaFX application.- The main class overrides
start
method defined inApplication
class (line 7). The method's argument is an object ofStage
type. AStage
type object (called primaryStage) is a window which is automatically created by the JVM when the application is launched.
Add the following content to the start
method:
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 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 onto the 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.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
Try out
Try to run the program given above.
Similar images were also made hundred years ago: https://www.wikiart.org/en/kazimir-malevich/black-square-1915
Session 7 |