setScene() method, JavaFX - javafx

I have a program with few fxml files so at different points of program different scene and layout is shown.
some point in a program:
mainStage.setScene(FXMLScene1);
...
later in a program:
mainStage.setScene(FXMLScene2);
...
later in a program:
mainStage.setScene(FXMLScene2);
I wonder what happens to old scene when I use setScene() several times?
There are very complicated methods to change scene(like this https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1) and my solution is just to make static refference to main stage at MainApplication class so I can manage it everywhere.
public class MainApplication extends Application {
public static Stage parentWindow;
#Override
public void start(Stage stage) throws Exception {
parentWindow = stage;
so it made me wonder if everything is allright with my concept...

You don't have to create a scene to flip screens. You can directly set the root node on the present scene, using setRoot() of the Scene.
This will save you the pain of creating a scene instance every time to want to change the content of your application.
You can use it:
Parent root = FXMLLoader.load(getclass.getResource("some-fxml.fxml"));
scene.setRoot(root);
Just keep in mind the Parent element being used in the FXML that you want to set as the Root Element. From the docs
The application must specify the root Node for the scene graph by setting the root property. If a Group is used as the root, the contents of the scene graph will be clipped by the scene's width and height and changes to the scene's size (if user resizes the stage) will not alter the layout of the scene graph. If a resizable node (layout Region or Control is set as the root, then the root's size will track the scene's size, causing the contents to be relayed out as necessary.
N.B. Please read through the EXAMPLE that you have provided, it uses setScreen( ) instead of setScene( ). The whole example has just one Scene and many Screens, where screens can be considered as any child of the scene graph
Additional data as per comments
If you go through the scene javadoc, you will find that Scene resizes itself to the root size, if no predefined size is present
The scene's size may be initialized by the application during construction. If no size is specified, the scene will automatically compute its initial size based on the preferred size of its content. If only one dimension is specified, the other dimension is computed using the specified dimension, respecting content bias of a root.
Different FXML have different size
In case you have different FXML that you want to set as ROOT nodes and each of them have different sizes.Futhermore, you want to re-size your stage in accordance to every FXML that you load, then you will have to re-initialize the Scene, there is no other way.
Parent root = FXMLLoader.load(getclass.getResource("some-fxml.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);

If you set a new scene on your stage and keep no reference to the old scene or objects in it, the old scene will be garbage collected and all resources associated with it will be thrown away (whenever the garbage collector in the Java Virtual Machine decides to do so). If you keep a reference to the old scene (e.g. assign it to a static final variable in your application), then the old scene resources will remain in memory until your application terminates.
If I change the root, how to make Stage change to the new size(size of Layout)?
Use stage.sizeToScene(), which will: "Set the width and height of this Window to match the size of the content of this Window's Scene." The stage sizing process when you invoke this call is similar to when you initially show a stage, but updated for the current scene's content and layout constraints.
The algorithm used is documented in the Scene javadoc: "The scene's size may be initialized by the application during construction. If no size is specified, the scene will automatically compute its initial size based on the preferred size of its content. If only one dimension is specified, the other dimension is computed using the specified dimension, respecting content bias of a root."
what is better, to change the whole scene, or just a root?
I don't think it makes much difference, choose whichever strategy makes the most sense to you.

Related

Switching To Primary Scene When Secondary Scene Is Closed

I am using JavaFX 11 and a newbie.
I have a single stage with two scenes: a primary scene that shows on start and a secondary scene that is switched to and shown when I press a certain button on the main scene. On the secondary scene, I want to be able to switch back to the main scene when I click the close X button on the top right of the window instead of having the entire application close.
I currently have a method for the cancel button that looks like this:
public void cancelButtonPushed(ActionEvent event) throws IOException {
Parent parent = FXMLLoader.load(getClass().getResource("ExampleMainScreen.fxml"));
Scene scene = new Scene(parent);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
}
This method allows me to switch back to the main scene when the Cancel button is pushed. However, I am lost trying to find something that can be used any time the user clicks the close X on the secondary scene.
First, get the terminology right, my guess is that you have two Stages. Scenes can be displayed inside those.
Second, Scene Builder (and the FXML it produces) does not manage stages, it only constructs nodes (and event handling for those nodes) that are placed inside scenes. So, you won't find the hooks you need to integrate with the window close functions in SceneBuilder or FXML.
Third, when a user wants to close a window (a stage is a kind of window), then an event will be emitted, which you can action onCloseRequest.
Fourth, somehow you have already managed to create a second stage, probably by calling new Stage(). This will provide you with a reference to the stage which you can set your close request on:
Stage secondaryStage = new Stage();
Stage setScene(secondaryScene);
secondaryStage.setOnCloseRequest(e -> primaryStage.show());
This will show your primary stage (which I guess you hid earlier), when the secondary stage is being closed, but before it has actually closed.
Next, read up on the Application lifecycle, specifically see the section which references Platform.setImplicitExit(boolean implicitExit):
If this attribute is true, the JavaFX runtime will implicitly shutdown when the last window is closed; the JavaFX launcher will call the Application.stop() method and terminate the JavaFX application thread. If this attribute is false, the application will continue to run normally even after the last window is closed, until the application calls exit(). The default value is true.
Note, that, you probably don't need to explicitly set the implicit exit flag if you handle the stage switching as outlined previously, but I provide the info for you in case you need to understand it.
Finally, consider whether you really should be creating new stages for your application and this particular task or just replacing the content in a single stage (similar to how a web browser works).

What is the main role of the scene in javafx?

A stage in javafx requires exactly one scene, and a scene requires exactly one root node.
So I want to know what's the main role of the scene? It seems like a scene connects two sides that can be connected directly without an intermediate.
I want juste to understand the logic.
Thank you.
Stage represents a native system window. Scene is the content of this window with JavaFX controls, nodes, stylesheets, etc.
You can change Scenes inside a Stage during your UI workflow without a need to create a new system window each time.

javafx load fxml into pane [duplicate]

I'm learning basic JavaFX right now, and I don't understand this statement from the book I'm reading: "No, a node such as a text field can be added to only one pane and once. Adding a node to a pane multiple times or to different panes will cause a runtime error." I can see from the UML diagram the book provides that it is a composition, but I don't understand why (library class code implementation) that is.
For instance, why does this result in a compile error? Isn't a new text field instantiated within the pane since it's a composition?
FlowPane pane = new FlowPane();
StackPane pane2 = new StackPane();
TextField tf = new TextField();
pane.getChildren().add(tf);
pane.getChildren().add(tf);
Also, why does the following run but not show the text field placed in pane?
FlowPane pane = new FlowPane();
StackPane pane2 = new StackPane();
TextField tf = new TextField();
pane.getChildren().add(tf);
pane2.getChildren().add(tf);
primaryStage.setScene(new Scene(pane));
primaryStage.show();
This is basically a (deliberate) consequence of the way the API is designed. Each Node has a collection of properties, including a parent property (the - one and only one - parent of the node in the scene graph), along with properties such as layoutX and layoutY which are the coordinates of the node in relation to its parent. Consequently, a node can only belong to one parent, and can only be added to a parent once (as it can only have one location in the parent). Organizing things this way enables a very efficient layout process.
Another way to think of this: suppose your first code block did what you wanted; so the text field tf appeared twice in the flow pane. What result would you expect to get from tf.getBoundsInParent()? Since tf appears twice in the parent, the API would not be able to give a sensible value for this call.
There are a couple of inaccuracies in statements you make in your question:
For instance, why does this result in a compile error? Isn't a new
text field instantiated within the pane since it's a composition?
First, technically, this is aggregation, not composition; though I'm not sure understanding the difference will aid your understanding of what is happening at this point.
Second, there is no compile error here; you get an error at runtime (the pane detects that the same node has been added twice; the complier has no way to check this).
Third, parents do not instantiate copies of the nodes you add to them. If so, you wouldn't be able to change the properties of nodes that were displayed. For example, if the FlowPane in your example instantiated a new TextField when you called pane.getChildren().add(tf);, and then displayed that new text field, then if you subsequently called tf.setText("new text"), it would have no effect, as it would not be changing the text of the text field that pane was displaying.
When you call pane.getChildren().add(...) you pass a reference to the node you want to be added; it is that node that is then displayed as a child of the pane. Any other implementation would produce pretty counter-intuitive behavior.
In your second code block:
pane.getChildren().add(tf);
pane2.getChildren().add(tf);
the second call implicitly sets the parent property of tf to pane2; consequently tf is no longer a child of pane. So this code has the effect of removing tf from the first parent, pane. As far as I am aware, this side-effect is not documented, so you probably should avoid writing code like this.
Try this:
TextField tf = new TextField();
TextField tf2 = new TextField();
pane.getChildren().add(tf);
pane.getChildren().add(tf2);
The reason you cannot add the same node twice is that only one node with the same specifications and dimensions can be viewable in the gui. It would be like copying an identical blue circle onto an original blue circle. To the user it looks the same, but it takes up more memory.

switch/quit fxml

My test app's flow uses multiple screens :
start(Stage stage) -> Screen 1
-> Screen 2
-> ...
I want to implement some of my screens in fxml, but can't figure what's the best practise way to switch between them.
How can i implement some quit-event mechanism in the screen 1 controller, when screen 1 reached its final state, and connect it to the "main loop" to delete screen 1 and update the scene with screen 2 ?
In my opinion, the best way to do it is loading your screens "on demand" whenever they are to be used, or even load them for just certain regions of your main screen (like a tab). To load a screen with FXML and then assign it to your main stage you would do something like:
Parent root = FXMLLoader.load(me.getClass().getResource("Scene2.fxml"));
Scene scene = new Scene( root );
stage.setScene(scene);
Another alternative is to use multiple stages, launch a stage whenever you need to do a specific action. This stage can be modal, so when it is closed, the main window stays behind:
final Stage stage = new Stage();
stage.initStyle(StageStyle.UNDECORATED);
stage.initOwner(owner_stage);
stage.initModality(Modality.APPLICATION_MODAL);
In this later case, the "quit mechanism" is just hiding the scene:
// from a label of your controller class
label.getScene().getWindow().hide();
In the first case, you would just load the main scene in your stage. Using multiple stages is the most common and straightforward way.

QGraphicsScene::changed() always returns a single rect sized to the app window

In a Qt 4.7.1 Windows app, a slot that's connected to QGraphicsScene::changed() is fired as expected but the dirty region count is always 1 and the rect size I get is always the same as my app window. I tried calling QGraphicsView::setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); but that didn't help.
Is there a way to tell Qt to only give me the area(s) of the page that changed?
An update in a QGRaphicsView is different from the one in a QGraphicsScene. Update in the view is caused by the need to repaint the view. With or without changing the scene. This typical is from window (resize) and view changes (scroll). An change in the scene will also trigger an update to the view.
A change in a scene is the change of the content of the scene. Like adding or removing a item, scaling or translating of the transformation. This will emit the changed() signal. All views displaying that scene will also update themselves for the display.
For example. Scrolling a view around will not generate any scene update since nothing in the scene changed. The paint() function of items in the scene will be called to repaint. But no changed() signal will be emitted from the scene.
If you changed the scale of the scene for instance, the whole scene changed. In addition to the whole repaint, the scene will emit changed() signal and indicates the whole scene changed. But if you add a new item to the scene, changed() should indicate only the rect of the new item.
If you want to know what part of the scene need to be repainted, in addition to calling QGraphicsView::setViewportUpdateMode(), you need to install a event filter to the view and check for QEvent::Paint. Note that the region and rect in QPaintEvent is in local coordinate of the view, which can be different from the scene. But QGraphicsView has many mapping functions to do the conversion.

Resources