Java:JFrame.setLocationRelativeTo(null)不使用OpenJDK 1.6.0_18将窗口置于Ubuntu 10.04/gnome 2.30.2的中心

cap*_*oop 10 java ubuntu gnome jframe

示例代码:

    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);
Run Code Online (Sandbox Code Playgroud)

截图http://img193.imageshack.us/img193/5296/screenshotrev.png

这是OpenJDK的错吗?我记得听说它不如Sun的那么好,但是因为它成了Ubuntu的标准,或者我决定与它一起使用的任何东西.该程序可能会在Windows上运行,所以我想我将不得不在那里检查...任何简单的方法以平台无关的方式解决这个问题,而不会破坏它已经工作的地方?

小智 20

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
Run Code Online (Sandbox Code Playgroud)

这将纠正问题并使Jframe居中

  • 基本上,在setLocationRelativeTo()之前调用pack().这是因为pack()计算窗口的大小,这是正确执行居中计算所必需的. (5认同)

jjn*_*guy 5

一种方法是手动定位窗口.请在致电后立即填写以下代码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);
Run Code Online (Sandbox Code Playgroud)

免责声明,这只是在Windows上测试过.

此外,你应该总是使用setPreferredSize()而不是setSize().