Chapter 23: Introducing the AWT: Working with Windows, Graphics, and Text 697
g.setFont(f);
if(fm == null) {
fm = g.getFontMetrics();
bl = fm.getAscent();
fh = bl + fm.getDescent();
space = fm.stringWidth(" ");
}
g.setColor(Color.black);
StringTokenizer st = new StringTokenizer(text);
int x = 0;
int nextx;
int y = 0;
String word, sp;
int wordCount = 0;
String line = "";
while (st.hasMoreTokens()) {
word = st.nextToken();
if(word.equals("<P>")) {
drawString(g, line, wordCount,
fm.stringWidth(line), y+bl);
line = "";
wordCount = 0;
x = 0;
y = y + (fh * 2);
}
else {
int w = fm.stringWidth(word);
if(( nextx = (x+space+w)) > d.width ) {
drawString(g, line, wordCount,
fm.stringWidth(line), y+bl);
line = "";
wordCount = 0;
x = 0;
y = y + fh;
}
if(x!=0) {sp = " ";} else {sp = "";}
line = line + sp + word;
x = x + space + w;
wordCount++;
}
}
drawString(g, line, wordCount, fm.stringWidth(line), y+bl);
}
public void drawString(Graphics g, String line,
int wc, int lineW, int y) {
switch(align) {
case LEFT: g.drawString(line, 0, y);
break;
case RIGHT: g.drawString(line, d.width-lineW ,y);
break;
case CENTER: g.drawString(line, (d.width-lineW)/2, y);
break;