What You Need to Know about the Scene Class in JavaFX
Like the Stage
class, the Scene
class is fundamental to JavaFX programs. In every JavaFX program, you use at least one instance of the Scene
class to hold the user-interface controls that your users will interact with as they use your program.
This table lists the more commonly used constructors and methods of the Scene
class.
Constructor | Description |
Scene(Parent root) |
Creates a new scene with the specified root node |
Scene(Parent root, double width, double height) |
Creates a new scene with the specified root node, width, and height |
Method | Description |
double getHeight() |
Gets the height of the scene |
double getWidth() |
Gets the width of the scene |
double getX() |
Gets the horizontal position of the scene |
double getY() |
Gets the vertical position of the screen |
void setRoot(Parent root) |
Sets the root node |
The following paragraphs explain some of the more interesting details of the constructors and methods of the Scene
class:
- All the
Scene
class constructors require that you specify the root node.
You can change the root node later by calling the setRoot
method, but it’s not possible to create a scene without a root node.
- You might be wondering why the root node is an instance of the
Parent
class rather than an instance of theNode
class. TheParent
class is actually a subclass of theNode
class, which represents a node that can have child nodes. There are several other subclasses ofNode
, which represent nodes that can’t have children; those nodes can’t be used as the root node for a scene. - You can set the scene’s initial size when you create it by specifying the
Width
andHeight
parameters.
If you don’t set the size, the scene will determine its own size based on its content.
- You can retrieve the size of the scene via the
getHeight
andgetWidth
methods.
There are no corresponding set
methods that let you set the height or width.
- In general, the size of the scene determines the size of the stage, provided that that scene is not smaller than the minimum size specified for the stage or larger than the maximum size.
- If the user resizes the stage, the size of the scene is resized accordingly.