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-2 of 2 total  RSS 

Center a text in Java Swing

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

String s;
int width, height;
Graphics g;

FontMetrics fm = getFontMetrics(ftDefault);
Rectangle2D textsize = fm.getStringBounds(s, g);
int xPos = (width - textsize.getWidth()) / 2;
int yPos = (height - textsize.getHeight()) / 2 + fm.getAscent();

g.drawString(s, xPos, yPos);

Convert string to anything

template <class T> T
fromString(const string &s) {
  T t;
  istringstream iss(s);
  iss >> t;
  return t;
}


You can then convert numbers in strings to other types like this:

double d = fromString<double>("10.2")
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS