问题描述
我有一个简单的问题.网格可以自动调整其中的对象大小以适应网格吗?
I have a simple question. Can a grid automatically resize the objects in it to fit the grid?
我想在一个网格上设置一个 max_height 和 max_width 以及一个 min-width 和 min-height 并在我的窗口中将该网格居中.
I want to set a max_height and max_width on a grid as well as a min-width and min-height and center that grid in my window.
在我的网格中,我想在所有位置添加 Spacer Square.每个垫片都有一个边框.所以它看起来像一个实际的网格.
In my grid, I want to add Spacer Square in all spots. Each spacer has a border. So it will look like an actual grid.
如果我的网格是 4x4,我希望有 16 个大正方形.
If my grid is 4x4, I want there to be 16 big squares.
如果我的网格是 16x18,我希望有 288 个方格.
If my grid is 16x18, I want there to be 288 squares.
两个选项都应占用一定数量的区域,288 平方选项的正方形比 16 选项小很多,以适应我的网格尺寸.
Both options should take up an area of a set amount, the 288 square option having squares a lot smaller than the 16 option in order to fit my grid dimensions.
我检查了 gridpane 文档,但我很困惑是否有适合我的选项.我不知道填充、边距、setmaxwidth、setmaxheight 之间的区别(试过这个,没有改变).
I checked the gridpane documentation, but am confused if there is an option for me. I don't know the difference between padding, margins, setmaxwidth, setmaxheight (tried this, didnt change a thing).
double dimension_x=100; //max_width of actual square/spacer/gridspace double dimension_y=100; //max_height of actual square/spacer/gridspace int grid_x=100; //number of rows int grid_y=100; //number of columns Rectangle[][] rectangles = new Rectangle[grid_x][grid_y]; GridPane grid = new GridPane(); double grid_max_x=800; double grid_max_y=600; grid.setHgap(1); grid.setVgap(1); grid.setPadding(new Insets(16)); //not sure what this does. Attempt Fail grid.setEffect(addEffect(Color.web("#202C2F"), .61, 12)); grid.setMaxHeight(grid_max_y); //does nothing that it APPEARS to me for (int x=0;x<grid_x;x++) { for(int y=0;y<grid_y;y++) { Rectangle temp = new Rectangle(dimension_x,dimension_y); grid.add(temp,x,y); } }
推荐答案
如果您想要一个可调整大小的矩形字段,则不需要网格.只需将它们放在窗格上并绑定到窗格大小:
If you want a field of resizable rectangles you don't need a grid. Just put them on Pane and bind to the pane size:
public void start(Stage stage) { Pane root = new Pane(); final int count = 7; //number of rectangles NumberBinding minSide = Bindings .min(root.heightProperty(), root.widthProperty()) .divide(count); for (int x = 0; x < count; x++) { for (int y = 0; y < count; y++) { Rectangle rectangle = new Rectangle(0, 0, Color.LIGHTGRAY); rectangle.xProperty().bind(minSide.multiply(x)); rectangle.yProperty().bind(minSide.multiply(y)); rectangle.heightProperty().bind(minSide.subtract(2)); rectangle.widthProperty().bind(rectangle.heightProperty()); root.getChildren().add(rectangle); } } stage.setScene(new Scene(root, 500, 500)); stage.show(); }