JavaFX - Get GridPane to fit parent

John Mikael Gundersen picture John Mikael Gundersen · Feb 7, 2013 · Viewed 42.8k times · Source

I have a simple GridPane showing a couple of labels and a button, but I cannot seem to get it to fit the parent StackPane. How would I go forth and make it so that it fills whatever container it is in?

    GridPane g = new GridPane();
    g.add(new Label("Categories"),0,0);
    g.add(new Label("Content"),1,0);        
    Button newCat = new Button("New Category");
    newCat.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
            System.out.println("Clicked");
        }
    });       
    g.add(newCat,0,1);
    g.setGridLinesVisible(true);
    StackPane root = new StackPane();
    root.getChildren().add(g);        
    Scene scene = new Scene(root, 300, 250);  
    primaryStage.setScene(scene);
    primaryStage.show();

UI is really not my forte and any help would be appreciated.

Answer

Videl picture Videl · Nov 2, 2013

You should see this link, especially the part about Percentage Sizing. If you have only two columns, I have found that code to work:

GridPane grid = new GridPane();
/* your code */
ColumnConstraints column1 = new ColumnConstraints();
column1.setPercentWidth(50);
grid.getColumnConstraints().add(column1);