Zeionic
Zeionic

Reputation: 11

JavaFx Multiple Layouts

I'm currently trying to create this Layout.

I've tried to use:

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

To let me create a menubar as well as a text field directly underneath it but it does not let me as the text field gets hidden by the menuBar.

I'm not sure which ones are needed in my case. I had a look at vbox - this is similar to what i what I need but I'm unsure how to add 2 tables in the last row with a gap

Would be a great help if you could point me in the direction needed.

Upvotes: 1

Views: 4396

Answers (1)

James_D
James_D

Reputation: 209330

StackPane is not a good choice here: it simply stacks child nodes on top of each other in z-order. I recommend you read the tutorial on layouts to get a full description of all the built-in layout panes, but one option is to use a VBox. To place the items in the bottom row, you could use an AnchorPane with one item anchored to the left and one to the right.

Here's an SSCCE using this approach:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TextArea;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class LayoutExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox(5);
        root.setPadding(new Insets(5));

        MenuBar menuBar = new MenuBar();
        menuBar.getMenus().add(new Menu("File"));

        TextArea textArea = new TextArea();
        VBox.setVgrow(textArea, Priority.ALWAYS);

        AnchorPane bottomRow = new AnchorPane();
        Label table1 = new Label("Table 1");
        table1.setStyle("-fx-background-color: gray");
        table1.setMinSize(200, 200);
        Label table2 = new Label("Table 2");
        table2.setStyle("-fx-background-color: gray");
        table2.setMinSize(200, 200);

        AnchorPane.setLeftAnchor(table1, 0.0);
        AnchorPane.setRightAnchor(table2, 0.0);
        bottomRow.getChildren().addAll(table1, table2);

        root.getChildren().addAll(menuBar, textArea, bottomRow);

        Scene scene = new Scene(root, 800, 800);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here

Another, similar, approach would be to use a BorderPane as the root, with the menu bar in the top, text area in the center, and anchor pane in the bottom.

Upvotes: 5

Related Questions