case LEFTRIGHT:
if(lineW < (int)(d.width*.75)) {
g.drawString(line, 0, y);
}
else {
int toFill = (d.width - lineW)/wc;
int nudge = d.width - lineW - (toFill*wc);
int s = fm.stringWidth(" ");
StringTokenizer st = new StringTokenizer(line);
int x = 0;
while(st.hasMoreTokens()) {
String word = st.nextToken();
g.drawString(word, x, y);
if(nudge>0) {
x = x + fm.stringWidth(word) + space + toFill + 1;
nudge--;
} else {
x = x + fm.stringWidth(word) + space + toFill;
}
}
}
break;
}
}
}
class MyMouseAdapter extends MouseAdapter {
TextLayout tl;
public MyMouseAdapter(TextLayout tl) {
this.tl = tl;
}
public void mouseClicked(MouseEvent me) {
tl.align = (tl.align + 1) % 4;
tl.repaint();
}
}
Let's take a closer look at how this applet works. The applet first creates several constants
that will be used to determine the alignment style, and then declares several variables. The
init( ) method obtains the text that will be displayed. It then initializes the font size in a
try-catch block, which will set the font size to 14 if the fontSize parameter is missing from
the HTML. The text parameter is a long string of text, with the HTML tag <P> as a paragraph
separator.
The update( ) method is the engine for this example. It sets the font and gets the baseline
and font height from a font metrics object. Next, it creates a StringTokenizer and uses it to
retrieve the next token (a string separated by whitespace) from the string specified by text. If
the next token is <P>, it advances the vertical spacing. Otherwise, update( ) checks to see if the
length of this token in the current font will go beyond the width of the column. If the line is full
of text or if there are no more tokens, the line is output by a custom version of drawString( ).
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home