private void setPreferredWidth ( ) { Element root = component . getDocument ( ) . getDefaultRootElement ( ) ; int lines = root . getElementCount ( ) ; int digits = Math . max ( String . valueOf ( lines ) . length ( ) , minimumDisplayDigits ) ; // Update sizes when number of digits in the line number changes if ( lastDigits != digits ) { lastDigits = digits ; FontMetrics fontMetrics = getFontMetrics ( getFont ( ) ) ; int width = fontMetrics . charWidth ( ' ' ) * digits ; Insets insets = getInsets ( ) ; int preferredWidth = insets . left + insets . right + width ; Dimension d = getPreferredSize ( ) ; d . setSize ( preferredWidth , HEIGHT ) ; setPreferredSize ( d ) ; setSize ( d ) ; } }
Calculate the width needed to display the maximum line number