Dimension (Container target, int maxWidth) { Insets insets = target.getInsets(); int height = insets.top + insets.bottom; int width = insets.left + insets.right; int rowHeight = 0; int rowWidth = insets.left + insets.right; boolean isVisible = false; boolean start = true; synchronized (target.getTreeLock()) { for (int i = 0; i < target.getComponentCount(); i++) { Component component = target.getComponent(i); if (component.isVisible()) { isVisible = true; Dimension size = component.getPreferredSize(); if (rowWidth + getHgap() + size.width > maxWidth && !start) { height += getVgap() + rowHeight; width = Math.max(width, rowWidth); rowWidth = insets.left + insets.right; rowHeight = 0; } rowWidth += getHgap() + size.width; rowHeight = Math.max(rowHeight, size.height); start = false; } } height += getVgap() + rowHeight; width = Math.max(width, rowWidth); if (!isVisible) { return super.preferredLayoutSize(target); } else { return new Dimension(width, height); } } }