Bounds of a String

P

Peter Ahrens

I will draw a rectangle with a string inside. Now I need the bounds of a
given string to get size of the rectangle. How can I get the bounds of a
String? I have found getStringBounds of Font. But the function needs a
FontRenderContext? Where can I get the FontRenderContext?

My function at the moment:

public void Draw(Graphics g)
{
g.setColor(Color.BLUE);

// g.getFont().getStringBounds(text, )
// g.drawString(text);

g.drawRect(10, 10, 20, 30);
}

Peter
 
A

Andrey Kuznetsov

I will draw a rectangle with a string inside. Now I need the bounds of a
given string to get size of the rectangle. How can I get the bounds of a
String? I have found getStringBounds of Font. But the function needs a
FontRenderContext? Where can I get the FontRenderContext?

better you use getStringBounds from FontMetrics
 
P

Peter Ahrens

Andrey Kuznetsov said:
better you use getStringBounds from FontMetrics
Okay, I try following

public void Draw(Graphics g){

g.setColor(Color.BLUE);
Rectangle2D rec = g.getFontMetrics().getStringBounds(title, g);
g.drawRect(rec.OUT_LEFT, rec.OUT_TOP, rec.OUT_RIGHT - rec.OUT_LEFT,
rec.OUT_BOTTOM - rec.OUT_TOP);
g.drawString(title, rec.OUT_LEFT, rec.OUT_TOP);
}

but this draws nothing. What's wrong?

Peter
 
K

klynn47

I'm not sure, but I think you're problem may have to do with the
baseline of the String. The coordinates in drawString indicate the
baseline of where the String will be drawn
 
A

Andrey Kuznetsov

public void Draw(Graphics g){
g.setColor(Color.BLUE);
Rectangle2D rec = g.getFontMetrics().getStringBounds(title, g);
g.drawRect(rec.OUT_LEFT, rec.OUT_TOP, rec.OUT_RIGHT - rec.OUT_LEFT,
rec.OUT_BOTTOM - rec.OUT_TOP);
;-)

g.drawRect(rec.x, rec.y, rec.width, rec.height);
g.drawString(title, rec.x, rec.y + rec.height);
 
P

Peter Ahrens

Andrey Kuznetsov said:
;-)

g.drawRect(rec.x, rec.y, rec.width, rec.height);
g.drawString(title, rec.x, rec.y + rec.height);
Where do you found x, y width and height in a Rectangle2D class? From
'g.getFontMetrics().getStringBounds(title, g);' do you get a Rectangle2D
class!

Peter
 
A

Andrey Kuznetsov

Where do you found x, y width and height in a Rectangle2D class? From
'g.getFontMetrics().getStringBounds(title, g);' do you get a Rectangle2D
class!
Recatangle2D is abstract class.
Subclasses of Recatangle2D are Rectangle, Rectangle2D.Float and
Rectangle2D.Double.
they all have this fields.

you can use methods getX(), getY(), getWidth() and getHeight() (comes from
RectangularShape)

you can use Recatangle2D#getBounds() to get Rectangle
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top