2

在此处输入图像描述

我正在做一个大学项目,我很难将组件与板网格对齐。该板将始终保持 1:1 的宽高比,但尺寸可能会有所不同。这是我尝试过的结果:

在此处输入图像描述

为什么百分比与我计算的实际图像尺寸 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));
        }
    }
}
4

2 回答 2

2

作为替代方案,使用BufferedImage#getSubimage()将图像分成全等的部分,如此处所示

于 2012-08-27T17:30:30.907 回答
2

GridLayout我已经想出了如何做到这一点,当您查看和之间的区别时,答案就来了MigLayout

发生的事情是我在使用时有空白空间(插图),GridLayout因为它强制所有单元格的大小相同。我在添加 1px 时注意到了这一点LineBorder

处理额外空间的方式MigLayout似乎是在单元格之间分配额外的像素,从而迫使它尽可能理想地修复容器。例如:

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");

在此处输入图像描述

它使用与此处显示的网格布局完全相同的容器和面板大小:(注意插图)

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));

在此处输入图像描述

于 2012-08-27T18:50:58.153 回答