How do I get buttons to fill a javafx gridpane?
I think you are asking how you get a node to fill the space allocated to its cell in a grid pane.
There are a couple of ways to do this. You can either use the static GridPane
methods to apply GridPane
-specific property settings to the nodes:
GridPane.setFillWidth(myButton, true);
GridPane.setFillHeight(myButton, true);
The other way is to specify column constraints and row constraints on the grid pane itself:
GridPane grid = new GridPane();
for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {
RowConstraints rc = new RowConstraints();
rc.setVgrow(Priority.ALWAYS) ; // allow row to grow
rc.setFillHeight(true); // ask nodes to fill height for row
// other settings as needed...
grid.getRowConstraints().add(rc);
}
for (int colIndex = 0; colIndex < numColumns; colIndex++) {
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS) ; // allow column to grow
cc.setFillWidth(true); // ask nodes to fill space for column
// other settings as needed...
grid.getColumnConstraints().add(cc);
}
In either case, you need to let the nodes grow in order for them to respect the request to grow that the grid pane makes. So, e.g.:
Button myButton = new Button("Click");
myButton.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
grid.add(myButton, 0, 0);
SSCCE (using row and column constraints method):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.stage.Stage;
public class KeyPad extends Application {
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
int numRows = 4 ;
int numColumns = 3 ;
for (int row = 0 ; row < numRows ; row++ ){
RowConstraints rc = new RowConstraints();
rc.setFillHeight(true);
rc.setVgrow(Priority.ALWAYS);
grid.getRowConstraints().add(rc);
}
for (int col = 0 ; col < numColumns; col++ ) {
ColumnConstraints cc = new ColumnConstraints();
cc.setFillWidth(true);
cc.setHgrow(Priority.ALWAYS);
grid.getColumnConstraints().add(cc);
}
for (int i = 0 ; i < 9 ; i++) {
Button button = createButton(Integer.toString(i+1));
grid.add(button, i % 3, i / 3);
}
grid.add(createButton("#"), 0, 3);
grid.add(createButton("0"), 1, 3);
grid.add(createButton("*"), 2, 3);
Scene scene = new Scene(grid);
primaryStage.setScene(scene);
primaryStage.show();
}
private Button createButton(String text) {
Button button = new Button(text);
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button.setOnAction(e -> System.out.println(text));
return button ;
}
public static void main(String[] args) {
launch(args);
}
}
I want to complete James_D's answer. I want to show how to achieve the same result using SceneBuilder.
In SceneBuilder select the Node to grow and set "Max Width" and "Max Height" to MAX_VALUE