Ensures that all JButton are the same size, and that the chosen size is sufficient to contain the content of any. - Java Swing

Java examples for Swing:JButton

Description

Ensures that all JButton are the same size, and that the chosen size is sufficient to contain the content of any.

Demo Code


//package com.java2s;
import java.awt.*;

import java.util.*;
import java.util.List;
import javax.swing.*;

public class Main {
    /**/*from   w  w w  .  j a va  2 s. co m*/
     * Ensures that all buttons are the same size, and that the chosen size is sufficient to contain the content of any.
     */
    public static void tieButtonSizes(JButton... buttons) {
        tieButtonSizes(Arrays.asList(buttons));
    }

    /**
     * Ensures that all buttons are the same size, and that the chosen size is sufficient to contain the content of any.
     */
    public static void tieButtonSizes(List<JButton> buttons) {
        int maxWidth = 0;
        int maxHeight = 0;
        for (JButton button : buttons) {
            Dimension buttonSize = button.getPreferredSize();
            maxWidth = (int) Math.max(buttonSize.getWidth(), maxWidth);
            maxHeight = (int) Math.max(buttonSize.getHeight(), maxHeight);
        }
        Dimension maxButtonSize = new Dimension(maxWidth, maxHeight);
        for (JButton button : buttons) {
            // Seemingly, to get the GTK+ LAF to behave when there are buttons with and without icons, we need to set every size.
            button.setPreferredSize(maxButtonSize);
            button.setMinimumSize(maxButtonSize);
            button.setMaximumSize(maxButtonSize);
            button.setSize(maxButtonSize);
        }
    }
}

Related Tutorials