This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
In order to center my JFrame or JDialog I created a getCenterScreen method that you can pass a Window object into and it will give you the center point. But I am wondering is this the best approach to go with?
This works. But the reason I ask is that this article here suggests centering a window simply by passing null into the setLocationRelativeTo method e.g.
Which approach would be most widely used? Is the second approach a bit of a hack?
The second approach is definitely not a hack - it's documented behaviour:
If the component is not currently showing, or c is null, the window is placed at the center of the screen. The center point can be determined with GraphicsEnvironment.getCenterPoint.
I used to do it the hard way, but these days I always use setLocationRelativeTo(null).
Also, the latter has one advantage - it ignores the not-usable part of the screen, like the task bar. It doesn't use the entire screen size through Toolkit.getScreenSize() but uses GraphicsEnvironment.getMaximumWindowBounds().