我正在尝试将 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)
Sets the location of the window relative to the specified component according to the following scenarios.
The target screen mentioned below is a screen to which the window should be placed after the
setLocationRelativeTo
method is called.
- If the component is
null
, or theGraphicsConfiguration
associated with this component isnull
, the window is placed in the center of the screen. The center point can be obtained with theGraphicsEnvironment.getCenterPoint
method.
另一方面
一些开发人员可能会建议您使用 Window#setLocationByPlatform(boolean flag)而不是 setLocationRelativeTo(...)
以遵循运行桌面应用程序的平台的 native 窗口系统的默认位置。这是有道理的,因为您的应用程序必须设计为在具有不同窗口系统和 PLAF 的不同平台上运行。
关于java - 将 JFrame 与 pack() 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25624435/