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.
GridPane lays out its children within a flexible grid of rows and columns. If a border and/or padding is set, then its content will be layed out within those insets. A child may be placed anywhere within the grid and may span multiple rows/columns.
To make a JavaFX GridPane visible you must add it to the JavaFX scene graph. To do so you must add the GridPane instance to a Scene object, or add the GridPane to a layout component which is added to a Scene object.
getColumnConstraints(). add(new ColumnConstraints(200)); By default the GridPane will resize rows/columns to their preferred sizes even if the gridpane is resized larger than its preferred size. To support dynamic column/row sizes, both contstaints class provides three property: min size, max size and preferred size.
To retrieve the coordinates from a node, you just need to invoke the GridPane static methods getColumnIndex() and getRowIndex() .
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);
In case anyone will be looking for an answer, this is how it worked for me:
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Window title");
GridPane grid = new GridPane();
gridSetup(grid); // Building my grid elements here (2 columns)
// Setting columns size in percent
ColumnConstraints column = new ColumnConstraints();
column.setPercentWidth(30);
grid.getColumnConstraints().add(column);
column = new ColumnConstraints();
column.setPercentWidth(70);
grid.getColumnConstraints().add(column);
grid.setPrefSize(WINDOW_WIDTH, WINDOW_HEIGHT); // Default width and height
grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
Scene scene = new Scene(grid, WINDOW_WIDTH, WINDOW_HEIGHT);
stage.setScene(scene);
stage.show();
}
With this setup the grid takes all space of the window and resizes automatically with the window.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With