JClass Elements

PreviousNextIndex

28

Word Wrap

Features of JCWordWrap  Methods  Examples


28.1 Features of JCWordWrap

JCWordWrap provides a static method called wrapText() that performs basic word-wrap logic on a String, given a line width in pixels and a delimiter to insert just before the line width is reached. While the delimiter is most often a newline, it can be any String.

The resulting String produced by JCWordWrap has lines no longer than the line width supplied as one of the parameters. Since the width of a line is measured in pixels, the number of words in a line depends on the FontMetrics currently in effect.

The other static method in this class is replace(). Its parameters are three Strings. The first parameter is the text String to be searched for occurrences of the second parameter. Any such occurrences are replaced with the third parameter.


28.2 Methods

Following is a list of the JCWordWrap methods:

wrapText()

This static method returns a word-wrapped String, given an input String, a FontMetrics object, a line width in pixels, a delimiter such as a newline, and a Boolean to indicate whether left-alignment is in effect. Word-wrap logic breaks lines by spaces, but provides no hyphenation logic. The original String is returned if the number of characters is less than 10.

replace()

Returns a String stripped of a delimiter, or replaces one String with another.


28.3 Examples

The code fragment shown here takes one rather long text String and constructs a reformatted one by adding newlines every so often. The new String s inserts newlines so that the lines never exceed 100 pixels, based on the current font.

...
FontMetrics fm = g.getFontMetrics(f);

String text = "It has flown away";
text += "The nightingale that called ";
text += "Waking me at midnight ";
text += "Yet its song seems "
text += "Still by my pillow.";


s = JCWordWrap.wrapText(text, fm, 100, delimiter, true);
Figure 57 :  It has flown away
The nightingale that
called Waking me at
midnight Yet its song
seems Still by my
pillow.

If the length for word wrapping is decreased to 50 pixels,

s = JCWordWrap.wrapText(text, fm, 50, delimiter, true);

The output String s is formatted as shown:

It has
flown
away The
nightingale
that called
Waking
me at
midnight
Yet its
song
seems
Still by my
pillow.

Taking this second case, use replace() to put the word -STOP- in place of a newline:

String s1 = JCWordWrap.replace(s, "\n", "-STOP-");

This would yield:

It has -STOP-flown -STOP-away The -STOP-nightengale -STOP-that called -STOP-Waking -STOP-me at -STOP-midnight -STOP-Yet its -STOP-song -STOP-seems -STOP-Still by my -STOP-pillow.

PreviousNextIndex