JavaFX Have multiple Panes in one scene?

僤鯓⒐⒋嵵緔 提交于 2019-12-10 14:10:37

问题


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?


回答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




回答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);


来源:https://stackoverflow.com/questions/33339427/javafx-have-multiple-panes-in-one-scene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!