在具有基于网格的背景的网格中排列组件 [英] Lining up components in a grid with grid-based background
问题描述
我正在从事一个大学项目,但在将组件与电路板网格对齐时遇到了困难.电路板将始终保持 1:1 的宽高比,但尺寸可能会有所不同.这是我尝试过的结果:
I'm working on a college project and I'm having difficulty lining up components with the board grid. The board will always maintain a 1:1 width to height ratio but the size can vary. Here is what I've tried which resulted in this:
为什么百分比与我计算的 1200x1200 的实际图像大小不一致?
Why are the percentages not lining up with what I calculated them to be for the actual image size of 1200x1200?
这是我的布局代码:
public class BoardPanel extends ViewComponent {
public static final int ROWS = 27;
public static final int COLS = 23;
private Board board = new Board();
private BufferedImage background = ResourceLoader.openImage("images/board.jpg");
public BoardPanel() {
this.add(board, "pos 4.5% 4.5%, width 76.5%, height 91%");
}
@Override
public void paintContent(Graphics2D g) {
g.drawImage(background, 0, 0, getHeight(), getHeight(), null);
}
private class Board extends ViewComponent {
public Board() {
setLayout(new GridLayout(ROWS, COLS, 1, 1));
for (int row = 0; row < ROWS; row++)
for (int col = 0; col < COLS; col++)
this.add(new Location(row, col));
}
}
}
推荐答案
我已经想出了如何做到这一点,当您查看 GridLayout
<之间的区别时,答案就出来了/strong> 和 MigLayout
.
I've figured out how to do this, and the answer comes when you look at the difference between GridLayout
and MigLayout
.
当我使用 GridLayout
时发生的情况是我有空白区域(插图),因为它强制所有单元格的大小相同.我在添加 1px LineBorder
时注意到了这一点.
What happened was I had empty space (insets) when I used GridLayout
because it forces all cells to be the same size. I noticed this when I added a 1px LineBorder
.
MigLayout
处理额外空间的方式似乎是在单元格之间分配额外的像素,从而迫使它尽可能理想地固定容器.例如:
The way MigLayout
handles extra space is it seems to distribute the extra pixels among the cells, thereby forcing it to fix the container as ideally as possible. For example:
this.setLayout(new MigLayout("ins 0, wrap " + COLS + ", gap 1", "grow", "grow"));
for (int row = 0; row < ROWS; row++)
for (int col = 0; col < COLS; col++)
this.add(new Location(row, col), "grow");
使用与此处显示的网格布局完全相同的容器和面板大小:(注意插图)
Which uses the exact same container and panel size as the grid layout shown here: (notice the insets)
this.setLayout(new GridLayout(ROWS, COLS, 1, 1));
this.setBorder(new LineBorder(Color.RED));
for (int row = 0; row < ROWS; row++)
for (int col = 0; col < COLS; col++)
this.add(new Location(row, col));
这篇关于在具有基于网格的背景的网格中排列组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!