Sample code:
JFrame jFrame = new JFrame("Test");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLocationRelativeTo(null);
jFrame.setSize(600, 600);
jFrame.pack();
// jFrame.setLocationRelativeTo(null); // same results
jFrame.setVisible(true);
Is this the OpenJDK's fault? I recall hearing it wasn't as good as Sun's, but since it became the standard for Ubuntu or whatever I decided to go along with it. The program is probably gonna run on windows, so I suppose I'm gonna have to check there... Any easy way to fix this in a platform independent way without breaking it where it already works?
Just set the size before setting the location.
Wrong:
jFrame.setLocationRelativeTo(null);
jFrame.setSize(600, 600);
Correct:
jFrame.setSize(600, 600);
jFrame.setLocationRelativeTo(null);
Note: Call setVisible() at last to prevent "jumping" of the window.
JFrame jFrame = new JFrame("Test");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//jFrame.setLocationRelativeTo(null);
jFrame.setSize(600, 600);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setLocationRelativeTo(null); //To center the code
This will correct the problem and center the Jframe
One way is to manually position the window. Put the following code right after your call to pack()
.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Point middle = new Point(screenSize.width / 2, screenSize.height / 2);
Point newLocation = new Point(middle.x - (jFrame.getWidth() / 2),
middle.y - (jFrame.getHeight() / 2));
jFrame.setLocation(newLocation);
Disclaimer, this was only tested on windows.
Also, you should always use setPreferredSize()
instead of setSize()
.
Just a precision : If you set the location before the size of the frame, you will center the top left corner of the window because the size is (0,0). You have to set the size before the location.
JFrame jFrame = new JFrame("Test");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(600, 600);
jFrame.pack();
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
It works well with me with OpenJDK-6 and Ubuntu 13.04. Try it on other platforms.
jFrame.validate();
This actually works better since pack can change the frame size, while validate
leaves the frame size alone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With