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





PostPosted: 2007-4-5 7:53:00 Top

java-programmer, getting the width and height of a String to draw a rectangle around it 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.

 
Daniel Pitts





PostPosted: 2007-4-5 8:13:00 Top

java-programmer >> getting the width and height of a String to draw a rectangle around it On Apr 4, 4:52 pm, "jakester" <email***@***.com> wrote:
> 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));

 
Esmond Pitt





PostPosted: 2007-4-5 8:37:00 Top

java-programmer >> getting the width and height of a String to draw a rectangle around it jakester wrote:

> 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/api/java/awt/Font.html#getStringBounds(char[],%20int,%20int,%20java.awt.font.FontRenderContext)
or one of the overloads of
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Font.html#getLineMetrics(java.text.CharacterIterator,%20int,%20int,%20java.awt.font.FontRenderContext)
 
 
Daniel Pitts





PostPosted: 2007-4-5 12:58:00 Top

java-programmer >> getting the width and height of a String to draw a rectangle around it On Apr 4, 5:37 pm, Esmond Pitt <email***@***.com> wrote:
> jakester wrote:
> > 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/api/java/awt/Font.html#getStringB...[],%20int,%20int,%20java.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.