Java:JFrame.setLocationRelativeTo(null) 不在 Ubuntu 10.04/gnome 2.30.2 和 OpenJDK 1.6.0_18 上的窗口居中

2022-01-24 00:00:00 ubuntu java jframe gnome

示例代码:

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

这是 OpenJDK 的错吗?我记得听说它不如 Sun 的好,但自从它成为 Ubuntu 或任何我决定采用它的标准之后.该程序可能会在 Windows 上运行,所以我想我必须在那里检查...有什么简单的方法可以以独立于平台的方式解决这个问题,而不会破坏它已经工作的地方?

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?

推荐答案

一种方法是手动定位窗口.在您调用 pack() 之后立即添加以下代码.

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

免责声明,这仅在 Windows 上进行了测试.

此外,您应该始终使用 setPreferredSize() 而不是 setSize().

Also, you should always use setPreferredSize() instead of setSize().

相关文章