/**
 *
 */
package com.github.apixandru.games.rummikub.ui;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * @author Alexandru-Constantin Bledea
 * @since Oct 12, 2015
 */
public final class ScalingGridPanel extends JPanel {

	/**
	 * @param rows
	 * @param cols
	 * @param childW
	 * @param childH
	 */
	public ScalingGridPanel(final int rows, final int cols, final int childW, final int childH) {
		super(new GridLayout(rows, cols));

		final Dimension computeDimensions = computeDimensions(rows, cols, childW, childH);

		final Insets buttonMargin = new Insets(0, 0, 0, 0);
		for (int ii = 0; ii < rows; ii++) {
			for (int jj = 0; jj < cols; jj++) {
				final JButton b = new JButton();
				b.setMargin(buttonMargin);
				b.setPreferredSize(new Dimension(childW, childH));
				add(b);
			}
		}

	}

	/**
	 * @param rows
	 * @param cols
	 * @param childW
	 * @param childH
	 * @return
	 */
	private static Dimension computeDimensions(final int rows, final int cols, final int childW, final int childH) {
		final int width = cols * childW;
		final int height = rows * childH;
		return new Dimension(width, height);
	}

}

@@ -53,16 +53,43 @@
 ub.ui;%0A%0A
+import java.awt.Component;%0A
 import j
@@ -103,24 +103,24 @@
 .Dimension;%0A
-
 import java.
@@ -340,16 +340,46 @@
 anel %7B%0A%0A
+%09private final double ratio;%0A%0A
 %09/**%0A%09 *
@@ -587,61 +587,33 @@
 %0A%0A%09%09
-final Dimension computeDimensions = computeDimensions
+this.ratio = computeRatio
 (row
@@ -1029,35 +1029,27 @@
 tic 
-Dimension computeDimensions
+double computeRatio
 (fin
@@ -1127,69 +1127,786 @@
 nal 
-int width = cols * childW;%0A%09%09final int height = rows * childH
+double width = cols * childW;%0A%09%09final double height = rows * childH;%0A%09%09return width / height;%0A%09%7D%0A%0A%09/* (non-Javadoc)%0A%09 * @see javax.swing.JComponent#getPreferredSize()%0A%09 */%0A%09@Override%0A%09public final Dimension getPreferredSize() %7B%0A%09%09final Dimension d = super.getPreferredSize();%0A%09%09final Component c = getParent();%0A%09%09final int parentHeight = c.getHeight();%0A%09%09if (c.getWidth() %3C d.getWidth() %7C%7C parentHeight %3C d.getHeight()) %7B%0A//%09%09%09we don't want it smaller than the preferred size (minimum)%0A%09%09%09return d;%0A%09%09%7D%0A%09%09final int height = (int) (c.getWidth() / this.ratio);%0A%09%09if (height %3C parentHeight) %7B%0A//%09%09%09if we allow a size greater than the parent size, it will ignore this directive%0A%09%09%09return new Dimension(c.getWidth(), height);%0A%09%09%7D%0A%09%09final int width = (int) (parentHeight * this.ratio)
 ;%0A%09%09
@@ -1933,17 +1933,23 @@
 (width, 
-h
+parentH
 eight);%0A

allow automatic resizing