使用基于网格的背景填充网格中的组件

时间:2012-08-27 14:28:03

标签: java swing miglayout

enter image description here

我正在做一个大学项目,我很难用电路板网格排列组件。电路板将始终保持1:1的宽高比,但尺寸可以变化。以下是我尝试过的结果:

enter image description here

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

2 个答案:

答案 0 :(得分:2)

作为替代方案,使用BufferedImage#getSubimage()将图像划分为全等部分,如here所示。

答案 1 :(得分: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");

enter image description here

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

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

enter image description here