JavaFX Have multiple Panes in one scene?

52,502

Solution 1

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

Solution 2

I would suggest you to create a "root"-Pane. In your case, you could use a BorderPane.

Example:

BorderPane root = new BorderPane();

Label centeredText = new Label("I want this text centered!");
Button unorganizedButton = new Button("Press me");

BorderPane.setAlignment(centeredText, Pos.CENTER);

root.setTop(centeredText);
root.setBottom(unorganizedButton);

Afterwards just call the constructor with the newly created pane.

Scene scene = new Scene(root, 500, 500);

Addition:

You could also just set new panes.

AnchorPane anchorPane = new AnchorPane();
root.setTop(anchorPane);
Share:
52,502
Hatefiend
Author by

Hatefiend

Updated on July 09, 2022

Comments

  • Hatefiend
    Hatefiend almost 2 years

    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?