替代包装()

Alternative to pack()

我正在制作一个地形生成器,我正在将超过一百万个 JPanel 加载到我的框架中,这需要一个多小时。我已经在 pack() 方法中隔离了大部分问题。有没有其他方法可以使用它,或者可以更快地使用它?这是我的一些代码:

    setLayout(new FlowLayout(0, 0, 0));
    System.out.println("Generating...");
    Chunk spawnChunk = new Chunk(this.mapSize);
    System.out.println("Done\nAdding Tiles...");
    for (double[] row : Chunk.tileData) {
        for (double d : row) {
            int v = (int) (20 - d / 500);
            if(v < 0) {
                v = 0;
            }
            else if (v > 20){
                v = 20;
            }
            add(new Tile(v, tileSize));
        }
    }
    System.out.println("Done\nPacking...");
    pack();
    System.out.println("Done\nRepainting...");
    repaint();
    System.out.println("Done");

注意:Tile 只是一个带有背景色的 JPanel

JPanel 太多了。我的建议 - 如果 'Tile is just a JPanel with a background color',那么只需使用一个 JPanel 自己进行自定义绘图。覆盖 paintComponent 方法并使用传递的 Graphics 对象绘制颜色。

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);  
    for ( int i = 0; i < numberOfTiles; i++ ){
        g.setColor(colorOfCurrentTile);
        g.fillRect(left, top, width, height);
    }
}