Ever wonder why there’s no method to wrap a String based on a certain number of characters in Swing? Me, too. Having the ability to wrap Strings can be especially useful if you don’t know how long your Strings are going to be, such as when you have translated text in a JOptionPane (or any other GUI element). Fortunately, we can write a nice utility class that does exactly what we need — StringWrapper.
The Code
Simply include this file in your project:
public class StringWrapper {
/**
* This method wraps a String based on a default
* number of max chars per line (60). This method
* is a helper which just calls {@link #wrap(String, int)}
*
* @param String line
* @return wrapped String
*/
public static String wrap( String line ) {
return wrap( line, 60 );
}
/**
* This method takes a String with presumably
* no line breaks and inserts a break in the
* first white space after the max number of
* chars specified. This is useful for wrapping,
* especially in JOptionPanes where wrapping is
* not a supported behavior.
*
* @param String line
* @param int maxCharsPerLine
* @return wrapped String
*/
public static String wrap( String line, int maxCharsPerLine ) {
char[] digit = line.toCharArray();
int count = 0;
for ( int i = 0; i < digit.length; i++ ) {
count++;
if ( count > maxCharsPerLine ) {
if ( digit[i] == ' ' ) {
digit[i] = '\n';
count = 0;
}
}
}
return new String( digit );
}
}
Usage
String reallyLongString = " ... ... ... "; String wrapped1 = StringWrapper.wrap( reallyLongString ); // Wrap by the default number of chars per line String wrapped2 = StringWrapper.wrap( reallyLongString, 100 ); // Wrap by setting your own number of chars per line
Enjoy!
Tags: string, string wrap, wrap
