The complete code for the StyledTextArea component.
- By Budi Kurniawan
- November 14, 2000
COMPONENT JAVA
AWT Styled Text Component
Budi Kurniawan
Listing 1. The complete code for the StyledTextArea component.
import java.awt.*;
import java.util.*;
public class myCanvas extends Canvas {
private static Vector lines = new
Vector();
private static Vector fonts = new
Vector();
private static Vector colors = new
Vector();
int width;
int leftMargin = 5;
int textHeight = 0;
private Color bgColor = Color.red;
public myCanvas(int width) {
this.width = width;
}
public void paint(Graphics g){
int y = 0;
for (int i=0; i<lines.size(); i++) {
g.setColor((Color)
colors.elementAt(i));
g.setFont((Font) fonts.elementAt(i));
FontMetrics fontMetrics =
g.getFontMetrics();
y += fontMetrics.getHeight();
g.drawString((String)
lines.elementAt(i), leftMargin, y);
}
} // end of paint
public void append(String str, Font font,
Color color) {
fonts.addElement(font);
colors.addElement(color);
setFont(font);
FontMetrics fontMetrics =
getFontMetrics(font);
textHeight += fontMetrics.getHeight();
setBounds(0, 0, width, textHeight +
fontMetrics.getDescent());
int stringLength = str.length();
int stringWidth =
fontMetrics.stringWidth(str);
int position = stringLength;
char ch = 0;
boolean loop=true;
while ((stringWidth > (width-
2*leftMargin)) && (position>0)) {
while (ch!=' ' && position>0) {
ch = str.charAt(--position);
}
// a very long word
if (position==0) {
position = stringLength;
while (stringWidth > width-
2*leftMargin) {
stringWidth =
fontMetrics.stringWidth(
str.substring(0, position--));
}
}
else {
stringWidth =
fontMetrics.stringWidth(
str.substring(0, position));
ch = 0;
}
}
lines.addElement(str.substring(0,
position));
if (position!=stringLength)
append(str.substring(position).trim(),
font, color);
/* this, called from here, does not work
in IE but works in Netscape
this.getParent().doLayout();
*/
repaint();
}
}
About the Author
Budi Kurniawan is an independent consultant who is currently working on a project for Kidz.net Ltd. in Sydney, Australia. He can be contacted at [email protected].