JavaFX Have multiple Panes in one scene?

Hatefiend picture Hatefiend · Oct 26, 2015 · Viewed 49.3k times · Source

I am trying to make an application which will have a date at the top (always automatically centered) and content at the bottom which is not going to be aligned to any direction.

I figured the best way to do this would be to have:

Pane normalLayout = new Pane();
StackPane centeredLayout = new Stackpane();
Label centeredText = new Label("I want this text centered!");
Button unorganizedButton = new Button("Press me");
centeredLayout.getChildren().add(centeredText);
normalLayout.getChildren().add(unorganizedButton);

But then I can't do something like:

Scene myScene = new Scene(centeredLayout, normalLayout, 500, 500);
Window myWindow = new Window();
myWindow.setScene(myScene);
myWindow.show();

So how can this be done? How can multiple panes exist on the same scene?

Answer

Marcel picture Marcel · Oct 26, 2015

The Scene it self can only have one root Pane. So if you want 2 panes in the Scene you need 3.

Scene  
  |   
  V
Root Pane (Vbox for example)
  |                   |
  V                   V
Pane1                Pane2

In your code this can look like this:

StackPane rootPane = new StackPane();
Scene scene = new Scene(rootPane,...);
Pane pane1 = new Pane();
Pane pane2 = new Pane();
rootPane.getChildren().addAll(pane1,pane2);

Depending on how your Application should be layouted you have to choose the right Pane implementations.

As a little Tip to get familiar whit all the Layout Containers try the SceneBuilder Application. http://gluonhq.com/open-source/scene-builder/

Maybe this link will help you understanding how layouting works in JavaFX: http://docs.oracle.com/javafx/2/scenegraph/jfxpub-scenegraph.htm https://docs.oracle.com/javafx/2/layout/builtin_layouts.htm