How to right justify fixed decimal point fields

Using drawString() how does one justify a column of fields with fixed decimal point, like a money amount, so that every item in the column is neatly aligned under the item above it. Currently I subtract the length of the string representing the decimal value from an offset like this:

g2.drawString(amountField, XOFFSET - (fontMetrics.stringWidth(amountField)), YOFFSET)

which achieves a degree of right justification, but its not perfect. Is there a better way like the swing

setHorizontalAlignment(mytextField.RIGHT)

?

Thanks.

[574 byte] By [1bloggs] at [2007-9-26 6:10:41]
# 1

That should be easy: cut the string in half.public void drawDecimalPointAlignedText(java.awt.Graphics g, String str, int x, int y) {

int i = str.indexOf(".");

String rightPart = str.substring(0, i);

g.drawString(str, x - getFontMetrics(getFont()).stringWidth(rightPart), y);

}

The coordinates of the decimal point will be approximately (x, y).

This method can be used from for instance the paint method:String str = "5.95";

drawDecimalPointAlignedText(g, str, 50, 20);

str = "99.99";

drawDecimalPointAlignedText(g, str, 50, 30);

jsalonen at 2007-7-1 15:00:10 > top of Java-index,Security,Cryptography...
# 2
jsalonenThat was a nice quick fix, it works pretty well. The only small problem is that "0.00" gets pushed slightly further to the right than the other fileds. Anyway, thanks for the code.
1bloggs at 2007-7-1 15:00:10 > top of Java-index,Security,Cryptography...
# 3

> The only small problem is that "0.00" gets pushed slightly

> furtherto the right than the other fileds.

Does it? By how many pixels?

I tested it and the decimal points were aligned perfectly with strings like "0.00", "11.00", "11.111", "111.11", and "Hello.world!"

Are you using a different font or is there any other explanation to this?

jsalonen at 2007-7-1 15:00:10 > top of Java-index,Security,Cryptography...
# 4
Im using Arial 10pt plain. What are you using? Also I am working with my laptop and printing to a pdf file. I havn't seen the result on my printer yet, there may be a difference. I'll print a hardcopy tomorrow when I get home. Thanks again.
1bloggs at 2007-7-1 15:00:10 > top of Java-index,Security,Cryptography...
# 5

Oh, you are printing...

That can introduce errors in quite a few places; I've mainly worked with display graphics so I don't know.

> Im using Arial 10pt plain. What are you using?

The default font; 10 pixel dialog plain (which is mapped to arial).

You are still using the FontMetrics of the font you are using, right?

jsalonen at 2007-7-1 15:00:10 > top of Java-index,Security,Cryptography...
# 6
Are Fontmetrics more-or-less deprecated in favor of LineMetrics, which take into account things like FractionalMetrics?
PaulFMendler at 2007-7-1 15:00:11 > top of Java-index,Security,Cryptography...