getting the width and height of a String to draw a rectangle around it

J

jakester

I have to draw (using Graphics or Graphics2D) a rectangle around a
String. How do I get the width and height of a String to draw a
rectangle around it? It seems there are many factors (i.e. Font/Face).
A simple example would help me.

Thanks.
 
D

Daniel Pitts

I have to draw (using Graphics or Graphics2D) a rectangle around a
String. How do I get the width and height of a String to draw a
rectangle around it? It seems there are many factors (i.e. Font/Face).
A simple example would help me.

Thanks.

if you have a Graphics object g.
g.getFontMetrics().getStringBounds();
loop up: java.awt.FontMetrics.

Alternatively:

JLabel label = new JLabel("My Text");
label.setBorder(BorderFactory.createLineBorder(Color.black));
 
E

Esmond Pitt

D

Daniel Pitts

jakester said:
I have to draw (using Graphics or Graphics2D) a rectangle around a
String. How do I get the width and height of a String to draw a
rectangle around it? It seems there are many factors (i.e. Font/Face).
A simple example would help me.

http://java.sun.com/j2se/1.5.0/docs...[], int, int, java.awt.font.FontRenderContext)
or one of the overloads ofhttp://java.sun.com/j2se/1.5.0/docs/api/java/awt/Font.html#getLineMet...)

Funny, he gets a reply from a Pitts and a Pitt.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top