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?

10
задан Glorfindel 6 August 2019 в 05:09
поделиться

1 ответ

Один из способов - вручную позиционировать окно. Поместите следующий код сразу после вызова 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);

Оговорка, это было проверено только на windows.

Кроме того, всегда используйте setPreferredSize() вместо setSize().

5
ответ дан 3 December 2019 в 14:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: