March 1, 2021
Hot Topics:

Fix a Broken Page by Breaking the String

  • By Scott Nelson
  • Send Email »
  • More Articles »

When All Else Fails, Compromise

There was one situation where, in even the previous solution, the text was still too long, taking up so many rows with wrapping that the cells were too tall. Here, a compromise had to made; agreeing to truncate the text at such times. The following method is a simple and effective solution:

 * Calculate the max string length based on the specified column
 * width, font size, and number of rows to display.
 * If the string length exceeds this number, truncate it.
 * @param String the string to be truncated
 * @param columnWidth width of the display column in pixels
 * @param fontSize font size used
 * @param numberOfRows number of lines to be displayed
 * @return String
public static String truncateString(String string,
   int columnWidth, int fontSize, int numberOfRows)
   if (string == null) { return ""; }

   String result = new String(string);
   float VARIANCE = 1.6f;

   Float maxDisplayLength = new Float(numberOfRows *
      (columnWidth / fontSize) * VARIANCE);
   int maxLen = maxDisplayLength.intValue();

   if (result.length() > maxLen)
      // -2 accommodates >>
      result = result.substring(0, maxLen - 2);
      if (!result.endsWith(" ") && (result.lastIndexOf(" ") > 0))
         result = result.substring(0, result.lastIndexOf(" "));

   return result;


This article covered one issue that is common and sometimes thought to be insolvable. In addition to providing a solution for this particular issue, it is probably more useful to notice that the solutions were arrived at by having the option of not solving them removed. This shows the disservice of the frequent use of the word "issue" when what you mean is "problem." "Issue" has become the office politic-speak for a problem. Issues can be stated, described, assigned, and postponed. Problems must be solved, preferably now. I'd rather have a problem than an issue any day, because a week from now most problems will be solved and the issues will still be there.

About the Author

Scott Nelson is a Senior Principal Web Application Consultant with well over 10 years of experience designing, developing, and maintaining web-based applications for manufacturing, pharmaceutical, financial services, non-profit organizations, and real estate agencies for use by employees, customers, vendors, franchisees, executive management, and others who use a browser. For information on how he can help with your web applications, please visit http://www.fywservices.com/ He also blogs all of the funny emails forwarded to him at Frequently Unasked Questions.

Page 3 of 3

This article was originally published on October 13, 2008

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date