Window size vs Scene size
The javafx.scene.Scene class is responsible for rendering JavaFX 2.0 content. A scene can be placed into various containers, for example, javafx.stage.Stage or javafx.embed.swing.JFXPanel. The size of a container may be or may not be equal to the size of the scene attached to it. In some cases you might want to specify the content size, e.g. when showing a confirmation dialog: the size of the window doesn't really matter, because its only purpose is to show visual content. In other cases, however, you might need to explicitly set a window size: imagine a floating palette panel that should be aligned with the main stage.
Let's examine some common scenarios.
1. Window width and height are known
Use the width and height properties of the javafx.stage.Window class:
Screen screen = Screen.getPrimary(); rectangle2D bounds = screen.getVisualBounds(); stage.setX(0); stage.setY(0); stage.setWidth(bounds.getWidth() / 2); stage.setHeight(bounds.getHeight() / 2); stage.setScene(scene); stage.setVisible(true);
2. Content dimensions are known
Just leave your window's width and height unassigned and set the size of the scene instead:
Scene scene = new Scene(root, 320, 240); stage.setScene(scene); stage.setVisible(true);
Scene width and height can be hardcoded as shown in the previous example, or they can calculated based on the scene's content:
Scene scene = new Scene(root); root.getChildren().add(new Button("I'm a JavaFX button")); stage.setScene(scene); stage.setVisible(true);
As a result, the window size exactly fits the size of the button:
3. Using the default platform width and height
Sometimes you don't want to specify window size at all. Although it's quite tricky in JavaFX 2.0, you still can implement it. You should neight explicitly set window width and height properties, nor place any content into your scene before the window is shown:
BorderPane pane = new BorderPane(); Scene scene = new Scene(pane); stage.setScene(scene); stage.setVisible(true); // After the stage is shown, populate the scene pane.setCenter(new WebView(new WebEngine("http://weblogs.java.net")));
Some hints you might find useful:
- Window and content dimensions can be combined together. For example, you can set window width explicitly and calculate its height based on the scene's height.
- Window location conforms to the same rules as a window size: you can either set its x and ycoordinates, or place some content and let JavaFX center your window in the screen, or let the native platform place the window to default location.
- javafx.embed.swing.JFXPanel as a scene container also inherits its size and forwards it to Swing. Therefore, if your layout manager respects components' preferred sizes, the JFXPanel component will be sized to fit JavaFX content in it.