views:

58

answers:

3

Before I re-invent the wheel (poorly), I'd like to know if there is a some existing Java code for wrapping text lines to a given maximum width. Ideally it would:

  • respect existing linebreaks
  • break up lines that exceed a maximum length on word boundaries
  • break up words whose length exceeds the maximum line width by inserting hyphens

Edit: there are no "pixels" here, only java.lang.String. "maximum width" refers to the number of characters on a line.

+2  A: 

Apache commons has WordUtils and wrap function in it:

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/WordUtils.html#wrap%28java.lang.String,%20int%29

Romario
A: 

What you want to do would only work if you display the results with a fixed-width font. Otherwise the number of characters in a line would not be the same from line to line. If that is fine with you, I would say that your's is a fairly uncommon case (especially considering hyphenation), so I doubt you will find ready-made solutions.

Ivan P
A: 

If you're trying to format some manner of documentation, there's also the old unix roff (or runoff) family of commands. You'd just have to insert formatting commands and let roff do the heavy lifting.

Tony Ennis