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.

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);
Reblog this post [with Zemanta]

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
2 + 12 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.