解决方法
我想你问的是如何在网格窗格中获取一个节点来填充分配给其单元格的空间.
有几种方法可以做到这一点.您可以使用静态GridPane方法将GridPane特定的属性设置应用于节点:
GridPane.setFillWidth(myButton,true); GridPane.setFillHeight(myButton,true);
另一种方法是在网格窗格本身上指定列约束和行约束:
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); }
在任何一种情况下,您都需要让节点增长,以便它们遵守网格窗格所做的增长请求.所以,例如:
Button myButton = new Button("Click"); myButton.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE); grid.add(myButton,0);
SSCCE(使用行和列约束方法):
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("#"),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); } }