Centering window in Java in a multi-display setup

Recently I have made another Java application with a nice splash screen. One important property of a splash screen is that it is displayed centered on the screen ... and since multi-monitor setups are not all that common nobody bothers to test this centering on more than one monitor.

Today I had a chance to test the application on my dual screen computer at work. Now, I don't know if this is just Linux problem but the splash screen got centered in the middle of both screens (half of the window on one screen and the other half on the other). Actually this is not just a problem of my application ... OpenOffice.org 2.4 does it too. But the problem is solvable by using the GraphicsEnvironment class.

#!java
Dimension w = getSize();    

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

Rectangle r = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();

Dimension d = new Dimension(r.width, r.height);

setLocation((d.width - w.width) / 2, (d.height - w.height) / 2);

Written on Oct. 7, 2008 at 10:49 a.m.
blog comments powered by Disqus