drawString appears offset in fullscreen!?

Hi.

I’m using Java2D in fullscreen on OS X.
The problem is that all graphics I draw is offset at 0,0 as they should be.
However, when using drawString I have to draw at 0, 10 to see the string at all.
It appears that drawString starts drawing at -10.
It’s not a inset problem as my fullscreen window is without decorations of any kind.

What gives? :slight_smile:

The coordinates you pass into drawString are interpretted as the base line of the text you want to render, not the top left.

I’m sure some1 else will be able to give you a more thorough explanation of how exactly the Fonts are measured.
Suffice to say, you need to look at java.awt.FontMetrics.

if you draw a string at 0,0 simply add fm.getMaxAscent() to your y position and everything will be fine

Fontmetrics fm = getFont().getFontMetrics();

have a look at sun’s java documentation and sun’s java font beginners tutorial, it will help you to get started in java

I had to figure this out recently to center some text. Here is what worked for me -


Font barFont = new Font("Serif", Font.BOLD, FONT_SIZE);
FontRenderContext frc = new FontRenderContext(null, true, false);

TextLayout tLayout = new TextLayout("My text here", barFont, frc);
Rectangle2D textRect = tLayout.getBounds();
int textXStart = (getWidth() - (int)textRect.getWidth()) / 2;
int textYStart = (BAR_HEIGHT + (int)textRect.getHeight()) / 2;
tLayout.draw(g, textXStart, textYStart);

This would center my text inside a progress bar I had at the bottom of my swing component.

AFAIK, the only difference between doing it this way and using the FontMetrics is that this will support doing things such as rotating your text and such. You would change the AffineTransform passed into the FontRenderContext.