How can I display a rectangle with centered text?

Scott Stanchfield

Note: You can do this most easily by using a JLabel component. Just set its border property to a LineBorder.

The trick to doing this with Graphics is to use the FontMetrics class to determine the size of the text and its Ascent.

Note that text is not written based on the upper-left corner of its bounding box -- it's written based on the left edge of its baseline. I like to add 1/2 leading to space it nicely.

To accomplish centered text in a box. Add the following code in a paint method (use paintComponent for Swing...)


public void paintComponent(Graphics g) {
  FontMetrics fm = getFontMetrics(getFont());
  String text = "Some text to display";
  
  int width = fm.stringwidth(text);
  int halfLeading = fm.getLeading()/2;
  int baseline = fm.getAscent() +
                 halfLeading;
  int height = fm.getHeight();

  g.drawRectangle(0,0,
                  width+halfLeading+1,
                  height+1);
  g.drawString(halfLeading, baseLine, text);

If you already know how wide or tall the box should be, you can adjust the position to accomodate. The above code draws the box nicely around the text. (You may want to add a wee bit more space to the width & height of the box -- YMMV)

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact