wood burning stoves 2.0*
The moose likes Swing / AWT / SWT and the fly likes Centering Window Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Centering Window" Watch "Centering Window" New topic
Author

Centering Window

Sean Keane
Ranch Hand

Joined: Nov 03, 2010
Posts: 581

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?


SCJP (1.4 | 5.0), OCJP (6.0), OCMJD
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4523
    
    5

Which approach would be most widely used?

The one which entails writing less code.

Is the second approach a bit of a hack?

Why not go through the source of Window#setLocationRelativeTo(Component c) and decide for yourself?


luck, db
There are no new questions, but there may be new answers.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

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().


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sean Keane
Ranch Hand

Joined: Nov 03, 2010
Posts: 581

Thanks guys. I think I will go with the second approach so!
Nam Ha
Ranch Hand

Joined: Aug 05, 2011
Posts: 50

Thanks guys for this useful tip.
I used to write the complex code, and I switch to the dead simple tommorow


Java Object Creation
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

i used to do it much like the first approach.

i also like the second approach better. much simpler and ignores the task bar.
i would just be sure to comment the line.


SCJP
Visit my download page
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Centering Window
 
Similar Threads
Centering Text in a JTable
Centering
centering g.drawString
centering a dialog
Centering dialogs in a multi-monitor environment?