Here you can find the source of getPreferredButtonSize(AbstractButton b, int textIconGap)
public static Dimension getPreferredButtonSize(AbstractButton b, int textIconGap)
//package com.java2s; //License from project: Open Source License import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.*; public class Main { public static Dimension getPreferredButtonSize(AbstractButton b, int textIconGap) { if (b.getComponentCount() > 0) { return null; }/* ww w. ja v a 2 s .c o m*/ Icon icon = (Icon) b.getIcon(); String text = b.getText(); Font font = b.getFont(); FontMetrics fm = b.getFontMetrics(font); Rectangle iconR = new Rectangle(); Rectangle textR = new Rectangle(); Rectangle viewR = new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE); SwingUtilities.layoutCompoundLabel((JComponent) b, fm, text, icon, b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewR, iconR, textR, (text == null ? 0 : textIconGap)); /* The preferred size of the button is the size of * the text and icon rectangles plus the buttons insets. */ Rectangle r = iconR.union(textR); Insets insets = b.getInsets(); r.width += insets.left + insets.right; r.height += insets.top + insets.bottom; return r.getSize(); } }