我试图将我过去习惯于JFrame
的pack()
居中,但我知道了,但我认为这不是干净的方式。
这就是我在atm上执行的方式:
JFrame window = new JFrame();
//filling
//window
//with
//stuff
window.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = (dim.width - window.getPreferredSize().width) / 2, y = (dim.height - window.getPreferredSize().height) / 2;
window.setBounds(x, y, window.getPreferredSize().width, window.getPreferredSize().height);
我将其填充后打包以得到最终的
PreferredSizes
,因此可以在setBounds
方法中使用这些值。但是我不喜欢打包后反弹。还有更好的主意吗?
最佳答案
要使窗口在屏幕中居中,您需要在pack()调用之后并且在使窗口可见之前立即调用window.setLocationRelativeTo(null)
:
JFrame window = new JFrame();
...
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
根据Window#setLocationRelativeTo(Component c)文档:
public void setLocationRelativeTo(Component c)
设置窗口相对于指定组件的位置
根据以下情况。
下面提到的目标屏幕是窗口所在的屏幕
应该放在
setLocationRelativeTo
方法调用之后。null
或与此相关的GraphicsConfiguration
组件是null
,窗口位于窗口的中心屏幕。中心点可以通过
GraphicsEnvironment.getCenterPoint
方法。 另一方面
一些开发人员可能建议您使用Window#setLocationByPlatform(boolean flag)而不是
setLocationRelativeTo(...)
来纪念桌面应用程序运行所在平台的本机窗口系统的默认位置。这是有道理的,因为您的应用程序必须设计为在具有不同窗口系统和PLAF的不同平台上运行。