Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

http://www.defined.de/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Center a text in Java Swing

Draws a string centered by calculating its position depending on the size.

   1  
   2  String s;
   3  int width, height;
   4  Graphics g;
   5  
   6  FontMetrics fm = getFontMetrics(ftDefault);
   7  Rectangle2D textsize = fm.getStringBounds(s, g);
   8  int xPos = (width - textsize.getWidth()) / 2;
   9  int yPos = (height - textsize.getHeight()) / 2 + fm.getAscent();
  10  
  11  g.drawString(s, xPos, yPos);
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS