All-You-Can-Gulp Steamin' Hot Hard-Core Java! No-compromise, professional, non-newbie tips, tricks and solutions. You're invited to join!

Sunday, April 21, 2002

Utility Function of the Day

The following method, while quite trivial, has been very useful for me. I use it to set the position for screen-centered splash-screens and to calculate the starting position for window-centered dialog-boxes. The method takes the size of the component to center, the size of the area ('canvas') the component is to be centered upon and returns the point that the component needs to be placed at for it to be centered.

The Code:
  /**

* Calculates the center-position for a component of a specified size on a specific "canvas".
* @param componentSize The size of the component to center
* @param canvasSize The size of the canvas target area to center to
* @return The centered position for the component, relative to the canvas' origin
*/
public static Point getCenterPosition(Dimension componentSize, Dimension canvasSize)
{
int x = (int)(((float)canvasSize.getWidth() / 2.0f) - ((float)componentSize.getWidth() / 2.0f));
int y = (int)(((float)canvasSize.getHeight() / 2.0f) - ((float)componentSize.getHeight() / 2.0f));

return new Point(x, y);
}


----

Enjoy!