private String createSizedString(final String message,final int pixels){
  FontMetrics fm=getFontMetrics(getFont());
  String word;
  StringTokenizer st=new StringTokenizer(message);
  int newWidth=pixels;
  while (st.hasMoreTokens()) {
    word=st.nextToken();
    newWidth=Math.max(newWidth,fm.stringWidth(word));
  }
  StringBuilder sb=new StringBuilder();
  StringBuilder cursb=new StringBuilder();
  boolean isNewLine;
  st=new StringTokenizer(message," \n",true);
  while (st.hasMoreTokens()) {
    word=st.nextToken();
    if (word.equals(" "))     continue;
    isNewLine=word.equals("\n");
    if (isNewLine || fm.stringWidth(cursb.toString() + word) > newWidth) {
      sb.append(cursb.toString());
      sb.append("\n");
      cursb=new StringBuilder();
    }
    if (!isNewLine) {
      cursb.append(word);
      cursb.append(" ");
    }
  }
  sb.append(cursb.toString());
  return sb.toString();
}

private String createSizedString ( final String message , final int pixels ) { FontMetrics fm = getFontMetrics ( getFont ( ) ) ; String word ; StringTokenizer st = new StringTokenizer ( message ) ; int newWidth = pixels ; while ( st . hasMoreTokens ( ) ) { word = st . nextToken ( ) ; newWidth = Math . max ( newWidth , fm . stringWidth ( word ) ) ; } StringBuilder sb = new StringBuilder ( ) ; StringBuilder cursb = new StringBuilder ( ) ; boolean isNewLine ; st = new StringTokenizer ( message , " \n" , true ) ; while ( st . hasMoreTokens ( ) ) { word = st . nextToken ( ) ; if ( word . equals ( " " ) ) continue ; isNewLine = word . equals ( "\n" ) ; if ( isNewLine || fm . stringWidth ( cursb . toString ( ) + word ) > newWidth ) { sb . append ( cursb . toString ( ) ) ; sb . append ( "\n" ) ; cursb = new StringBuilder ( ) ; } if ( ! isNewLine ) { cursb . append ( word ) ; cursb . append ( " " ) ; } } sb . append ( cursb . toString ( ) ) ; return sb . toString ( ) ; }
convert the input string to a string with newlines at the closest word to the number of pixels specified in the ' pixels ' parameter .
