While working with Java, I find it hard to position my main window in the center of the screen when I start the application.
Is there any way I can do that? It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.
If you explicitly
setPreferredSize(new Dimension(X, Y));
then it is better to use:setLocation(dim.width/2-this.getPreferredSize().width/2, dim.height/2-this.getPreferredSize().height/2);
i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.
in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'. you will need first to set the Form Size Policy to 'Generate Resize Code'.
You can call
JFrame.setLocationRelativeTo(null)
to center the window. Make sure to put this beforeJFrame.setVisible(true)
As simple as this...
or if you are using a frame then set the frame to
For clarification, from the docs:
You'll get the size set, after you add this:
frame.setLocationRelativeTo(null);