> 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));
> 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.t
ext.CharacterIterator,%20int,%20int,%20java.awt.font.FontRenderContext)
Daniel Pitts - 05 Apr 2007 05:57 GMT
> > 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
[quoted text clipped - 3 lines]
> http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Font.html#getStringB...[],%20in
t,%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.