Dimension () { if (isPreferredSizeSet()) return super.getPreferredSize(); int width = 0; FontMetrics fontMetrics = getFontMetrics(getFont()); for (String line : getText().split("\n")) { width = Math.max(width, fontMetrics.stringWidth(line)); } Dimension d = super.getPreferredSize(); Insets insets = getInsets(); d.width = Math.min(d.width, width + insets.left + insets.right); return d; }