Java: JFrame.setLocationRelativeTo(null) not centering the window on Ubuntu 10.04 / gnome 2.30.2 with OpenJDK 1.6.0_18

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


jFrame.validate();

This actually works better since pack can change the frame size, while validate leaves the frame size alone.