Sets the items in Components to the same size. - Java Swing

Java examples for Swing:JComponent

Description

Sets the items in Components to the same size.

Demo Code

/**//w  w  w.  ja v  a2s  .  c  o  m
 * some swing helpers from
 * http://www.javapractices.com/topic/TopicAction.do?Id=152
 * 
 * @author Hirondelle Systems (code snippets used on BSD license)
 */
//package com.java2s;

import java.awt.Dimension;

import java.util.Iterator;

import javax.swing.JComponent;

public class Main {
    /**
     * Sets the items in <tt>aComponents</tt> to the same size.
     * 
     * <P>
     * Sets each component's preferred and maximum sizes. The actual size is
     * determined by the layout manager, which adjusts for locale-specific
     * strings and customized fonts. (See this <a
     * href="http://java.sun.com/products/jlf/ed2/samcode/prefere.html">Sun
     * doc</a> for more information.)
     * 
     * @param aComponents
     *            items whose sizes are to be equalized
     */
    public static void equalizeSizes(java.util.List<JComponent> aComponents) {
        Dimension targetSize = new Dimension(0, 0);
        for (JComponent comp : aComponents) {
            Dimension compSize = comp.getPreferredSize();
            double width = Math.max(targetSize.getWidth(),
                    compSize.getWidth());
            double height = Math.max(targetSize.getHeight(),
                    compSize.getHeight());
            targetSize.setSize(width, height);
        }
        setSizes(aComponents, targetSize);
    }

    private static void setSizes(java.util.List<JComponent> aComponents,
            Dimension aDimension) {
        Iterator<JComponent> compsIter = aComponents.iterator();
        while (compsIter.hasNext()) {
            JComponent comp = (JComponent) compsIter.next();
            comp.setPreferredSize((Dimension) aDimension.clone());
            comp.setMaximumSize((Dimension) aDimension.clone());
        }
    }
}

Related Tutorials