添加具有 86,000 个组件的 JPanel

Adding a JPanel with 86,000 Components

所以最近发现了Conway's Game of Life,自然就上瘾了。没过多久我就发现我的计算机 CPU 非常受限。我还发现,无论出于何种原因,我都无法将具有许多 JComponentsJPanel 添加到 JFrame

所以我有一个 loop86,400 JLabels 添加到 JPanel,这在大约 1 秒内发生,但是将此 JPanel 添加到JFrame 大约需要 2 分钟。

我知道我可以使用 java.awt.Graphics,但我更愿意使用 JLabels,因为它们会自动调整大小。

所以我的问题是:为什么将 JPanel 添加到 JFrame 需要这么长时间,我该如何解决?

使用 java.awt.Graphics,我能够消除这段长时间的延迟:

public void render(int[][] cells) {

    int cellHeight = image.getHeight() /  cells.length;
    int cellWidth = image.getWidth() /  cells[0].length;

    for (int y = 0; y < cells.length; y++) {
        for (int x = 0; x < cells[y].length; x++) {

            int col = colors[cells[y][x]].getRGB();
            fillSquare(x * (cellWidth), y * (cellHeight), cellWidth, cellHeight, col);
        }
    }
}

// Could pass a java.awt.Rectangle here
private void fillSquare(int xPos, int yPos, int width, int height, int col) {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            pixels[(x + xPos) + (y + yPos) * image.getWidth()] = col;
        }
    }
}

@Override
public void paint(Graphics g) {
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

对于此方法,保持 JFrame 的大小与单元格数量成比例很重要,这样 JFrame 中就没有未使用的 space。