code: private static Point computeGridSize(
          Container container, int numComponents, double aspect)
      {
          double containerSizeX = container.getWidth();
          double containerSizeY = container.getHeight();
          double minTotalWastedSpace = Double.MAX_VALUE;
          int minWasteGridSizeX = -1;
          for (int gridSizeX = 1; gridSizeX <= numComponents; gridSizeX++)
          {
              int gridSizeY = numComponents / gridSizeX;
              if (gridSizeX * gridSizeY < numComponents)
              {
                  gridSizeY++;
              }
              double cellSizeX = containerSizeX / gridSizeX;
              double cellSizeY = containerSizeY / gridSizeY;
              double wastedSpace =
                  computeWastedSpace(cellSizeX, cellSizeY, aspect);
              double totalWastedSpace = gridSizeX * gridSizeY * wastedSpace;
              if (totalWastedSpace < minTotalWastedSpace)
              {
                  minTotalWastedSpace = totalWastedSpace;
                  minWasteGridSizeX = gridSizeX;
              }
          }
          int gridSizeX = minWasteGridSizeX;
          int gridSizeY = numComponents / gridSizeX;
          if (gridSizeX * gridSizeY < numComponents)
          {
              gridSizeY++;
          }
          return new Point(gridSizeX, gridSizeY);
      }
docs: Compute a grid size for the given container, for the given number
  of components with the specified aspect ratio, optimizing the
  number of rows/columns so that the space is used optimally.
  
  @param container The container
  @param numComponents The number of components
  @param aspect The aspect ratio of the components
  @return A point (x,y) storing the (columns,rows) that the
  grid should have in order to waste as little space as possible