JavaFX
A JavaFX program extends the Application
class.
Your program must include a start()
method to override the
abstract start()
method of that class.
The method takes a parameter that is a reference to a Stage
, which
represents the window that the program controls.
The Stage
is created by the graphics system and handed to your start()
method.
Your program does not have to create it.
A Stage
displays a Scene
,
which contains a scene graph made up of the graphics objects to be displayed.
The the root of the scene graph is often a Group
.
Here is a program that draws a single rectangle.
The scene graph consists of a Group
which contains a Rectangle
object.
import javafx.application.*; import javafx.stage.*; import javafx.scene.*; import javafx.scene.shape.*; import javafx.scene.paint.*; public class DrawRectangle extends Application { final double sceneWidth=400, sceneHeight= 300; final double centerX=sceneWidth/2, centerY=sceneHeight/2; public void start(Stage stage) { double scale = 0.9; // make the rect 0.9 the size of the scene Group root = new Group( ); double width=sceneWidth*scale, height=sceneHeight*scale; Rectangle rect = new Rectangle( centerX-width/2, centerY-height/2, width, height ); rect.setStrokeWidth( 2.0 ); // the stroke is the border of the rectangle rect.setStroke( Color.RED ); // rect.setFill( Color.TRANSPARENT ); // the fill is the inside of the rectangle root.getChildren().add( rect ); // the rect is put into the scene graph // the scene graph is put into the scene Scene scene = new Scene(root, sceneWidth, sceneHeight, Color.GHOSTWHITE ); stage.setTitle("One Rectangle"); // the scene graph is put into the stage stage.setScene(scene); stage.show(); } }
Here is the constructor for Rectangle
objects.
Rectangle(double x, double y, double width, double height)
Create a rectangle with specified width and height with upper left corner at (x,y)
The program centers the rectangle in the scene by placing the upper left corner at half the width and half the height away from the center of the scene.
In a JavaFX scene, where is the origin (0,0)?