views:

129

answers:

1

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?

A: 

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

jjnguy
Same thing happens. I wonder if it's my monitor?
captain poop
@captain, you get the same results as in your question?
jjnguy
@Justin yep :((
captain poop
@captain, try running it without dividing getWidth and getHeight by 2. So: `new Point(middle.x - (jFrame.getWidth()), middle.y - (jFrame.getHeight()));`
jjnguy
@Justin same thing happened. It's weird because I can set the location normally, but neither of those methods worked. Well, I realize that the problem is the jFrame getWidth() and getHeight(). Width is 10, Height is 30, even though I've set the jframe size to 600 x 600.
captain poop
@captain, what do you mean by "set the location normally'?
jjnguy
@cap, also, use `setPreferredSize()` instead of `setSize()`
jjnguy
@Justin: aha! the problem was setSize(). I had to use setPreferredSize(). Thanks!
captain poop
@cap, glad I could help.
jjnguy