gpt4 book ai didi

layout - 如何获取按钮来填充 javafx 网格 Pane ?

转载 作者:行者123 更新时间:2023-12-04 05:17:10 26 4
gpt4 key购买 nike

Java Swing 有 GridLayout ,它允许您指定小部件数组的大小,例如 3X4。然后小部件填充它们占据的面板。你如何在 JavaFX 中获得类似的效果?

最佳答案

我想您是在问如何让节点填充网格 Pane 中分配给其单元格的空间。

有几种方法可以做到这一点。您可以使用静态 GridPane申请方法GridPane - 节点的特定属性设置:

GridPane.setFillWidth(myButton, true);
GridPane.setFillHeight(myButton, true);

另一种方法是在网格 Pane 本身上指定列约束和行约束:
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);
}

在任何一种情况下,您都需要让节点增长,以便它们遵守网格 Pane 提出的增长请求。所以,例如:
Button myButton = new Button("Click");
myButton.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
grid.add(myButton, 0, 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("#"), 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);
}
}

关于layout - 如何获取按钮来填充 javafx 网格 Pane ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com