• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

How to use stringWidth(String str)

Hi,
I want to use the method public int stringWidth(String str), from java.awt.FontMetrics, to check how wide a String gets when I draw it to the display.

So if I have the following code:
Font f = new Font("Times New Roman", 0, 20);
setFont(f);
String str = "Hello World";
int string_width;

How can I get the width of which the string is drawn?

I have tried:
string_width = stringWidth(str); //error: Undefined name stringWidth

I also tried to make an instance of FontMetrics
FontMetrics fm = new FontMetrics(f);//error: Cannot 'new' an instance of abstract class 'FontMetrics'


0
Krafer
Asked:
Krafer
  • 2
  • 2
1 Solution
 
mwibbelsCommented:
java.awt.Font f = ...
java.awt.FontMetrics fontMetrics = java.awt.Toolkit.getDefaultToolkit().getFontMetrics(f);

or (if you've got a reference to a Component):

java.awt.FontMetrics fontMetrics = c.getToolkit().getFontMetrics(f);

where c is the Component reference.

0
 
diakovCommented:
FontMetrics fm = getToolkit().getFontMetrics(font);
int w = fm.stringWidth("asdasd");

Cheers,
  Nik
0
 
diakovCommented:
OOPS! please reject, I didn't see that somebody else answered.

Nik

P.S. Sorry MWibbels.
0
 
KraferAuthor Commented:
Thanks to both of you.
mwibbels please lock the question so I can grade your answer.
0
 
mwibbelsCommented:
Ok, thanks.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now