centering components

just wrote this for my little app in progress (highscore server). nothing fancy but it has it’s place in some tool package. i just use it to center my JFrame and other stuff.


public void centerComponent(Component c) {
  GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice device = env.getDefaultScreenDevice();
  DisplayMode displayMode = device.getDisplayMode();
  int screenWidth = displayMode.getWidth();
  int screenHeight = displayMode.getHeight();
  int componentWidth = c.getWidth();
  int componentHeight = c.getHeight();
  c.setLocation(screenWidth/2 - componentWidth/2, screenHeight/2 - componentHeight/2);
}

Hmm. You know, if you use Java 1.4 or higher, you can use the setLocationRelativeTo method on Window (which JFrame of course extends) to do much of this.

Here’s a link to the documentation:
http://java.sun.com/j2se/1.4.1/docs/api/java/awt/Window.html#setLocationRelativeTo(java.awt.Component)

Setting the parameter to null makes the Window center itself onscreen.

hah, cool. much better