![]() ![]() ![]() |
28
Word Wrap
Features of JCWordWrap
Methods
Examples
28.1 Features of JCWordWrap
JCWordWrap
provides a static method calledwrapText()
that performs basic word-wrap logic on aString
, 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 anyString
.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 theFontMetrics
currently in effect.The other static method in this class is
replace()
. Its parameters are threeStrings
. 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:
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
It hass
is formatted as shown:
flown
away The
nightingale
that called
Waking
me at
midnight
Yet its
song
seems
Still by my
pillow.Taking this second case, use
String s1 = JCWordWrap.replace(s, "\n", "-STOP-");replace()
to put the word -STOP- in place of a newline:
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.
![]() ![]() ![]() |