This site requires JavaScript, please enable it in your browser!
Greenfoot back
Pointifix
Pointifix wrote ...

2014/2/25

Size of Fonts

Pointifix Pointifix

2014/2/25

#
Hi guys, i got another little "problem". I used the font "Monospaced" so that the letters are all the same size, but how do i get the width of a letter so i can center a text with every length in my screen? Are there any Ideas to this?
bourne bourne

2014/2/25

#
Take a look into the FontMetrics class, particularly its charswidth method. Something like this: String text; Graphics2D g; ... FontMetrics fm = g.getFontMetrics(); int width = fm.charsWidth(text.toCharArray(), 0, text.length()); g.drawString(text, middleXCoord - width / 2, y); ... g.dispose();
Pointifix Pointifix

2014/2/25

#
ah ok thanks, the class i have to import is import java.awt.FontMetrics; right? i have imported this but he cant find getFontMetrics()
bourne bourne

2014/2/25

#
Correct. And getFontMetrics belongs to the Graphics/Graphics2D class. The variable g should be assigned: if you are using GreenfootImage,
1
g = myGreenfootImage.getAwtImage().createGraphics();
Pointifix Pointifix

2014/2/25

#
with graphics import its still not working whats wrong with this?
1
2
3
FontMetrics fm = getFontMetrics(new Font("MONOSPACED",Font.BOLD,50));
         
        getBackground().drawString("Highscore Top 5",getBackground().getWidth()/2-fm.StringWidth("Highscore Top 5")/2,50);
bourne bourne

2014/2/25

#
FontMetrics fm = g.getFontMetrics();
not
FontMetrics fm = getFontMetrics(...);
Pointifix Pointifix

2014/2/25

#
hui its working great thanks to you bourne ;) but i think its stupid that i need so much code just for centerering my text, but jeah
bourne bourne

2014/2/25

#
Edit: Never mind. And yes, but it is what it is. It gives you control without layering tons of overhead (too much functionality for general use).
You need to login to post a reply.