Workaround for Zero Font Width problem in pJava
843849Aug 16 2001 — edited Aug 27 2001skip down a bit if you don't like stories
I need to use a JTabbedPane and a JTree, but in pjava it won't display right because the font width is set to zero (this is also why text is not centered in buttons/labels/etc).
Here's my "stack trace" if you will:
To display Text, the paint method (on any swing component containing text), calls the LayoutComponentLabel() Method on the SwingUtilities class, and passes a bunch of parameters, one of which is a reference to a Rectangle object representing the bounding rectangle for the text.
To fit this rectangle, SwingUtilities uses a method computeStringWidth.
in that method, If you are java 2 (remember our favorite fix for Jeode?) It calls a method on Java.awt.Fontmetrics called StringWidth(). This method takes into account kerning and other Java2D features. If not (and all on pJava aren't)- it first calls FontMetrics.getWidths() to get an array of widths for every char<255, then it adds the width of each character to get a result.
Here's where the problem lies: the java.awt.FontMetrics class and the java.awt.Toolkit class are implemented by the VM. Somebody forgot to implement the FontMetrics.getWidths() property. it should return an array like [0,0,0...7,8,9,7,5,3,...8] but in pJava it returns [0,0,0...0,0,0]- the result is it adds up a lot of zeros.
HERE'S MY WORKAROUND*:
Contrary to what the documentation says, FontMetrics.StringWidth() works fine in pJava.
So in SwingUtilities.java simply change the method computeStringWidth()
From:
public static int computeStringWidth(FontMetrics fm,String str) {
if (is1dot2) {
// You can't assume that a string's width is the sum of its
// characters' widths in Java2D -- it may be smaller due to
// kerning, etc.
return fm.stringWidth(str);
}
int w[] = fm.getWidths();
int i,c;
int result = 0;
char ch;
for(i=0,c=str.length() ; i < c ; i++) {
ch = str.charAt(i);
if(ch > 255)
return fm.stringWidth(str);
else
result += w[(int)ch];
}
return result;
}
To:
public static int computeStringWidth(FontMetrics fm,String str) {
return fm.stringWidth(str);
}
Now, plug it back into swingall.java and Voila! Everything with text looks right!
Hope this all made sense.
Good luck!
-Ari
*Caveat- I just discovered this today, and I don?t have time to test it extensively. All I know is it works for my app. Also this workaround may open up another can of worms in some other swing function that I don?t use. Anybody encounters such an error, please post here.