Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);

screenshot

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?

like image 569
captain poop Avatar asked Aug 13 '10 19:08

captain poop


5 Answers

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.

like image 94
trinity420 Avatar answered Sep 26 '22 02:09

trinity420


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

like image 38
Evan Avatar answered Oct 20 '22 14:10

Evan


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

like image 41
jjnguy Avatar answered Oct 20 '22 16:10

jjnguy


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.

like image 4
YoannFleuryDev Avatar answered Oct 20 '22 15:10

YoannFleuryDev


jFrame.validate();

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

like image 3
Nicholas Duchon Avatar answered Oct 20 '22 15:10

Nicholas Duchon