排队组件在网格与网格化背景(Lining up components in a grid with

2019-09-21 17:44发布

我工作的一个大学项目,我有困难排队组件与电路板的网格。 该板将始终保持为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));
        }
    }
}

Answer 1:

作为替代方案,可以使用BufferedImage#getSubimage()到将图像划分为块全等,如图这里 。



Answer 2:

我已经想通了如何做到这一点,当你看之间的差别,答案来得GridLayoutMigLayout

发生了什么事我有空余空间(插图),当我用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));



文章来源: Lining up components in a grid with grid-based background