java - 将 JFrame 与 pack() 结合使用

标签 java swing jframe window pack

我正在尝试将 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 the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.

另一方面

一些开发人员可能会建议您使用 Window#setLocationByPlatform(boolean flag)而不是 setLocationRelativeTo(...) 以遵循运行桌面应用程序的平台的 native 窗口系统的默认位置。这是有道理的,因为您的应用程序必须设计为在具有不同窗口系统和 PLAF 的不同平台上运行。

关于java - 将 JFrame 与 pack() 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25624435/

相关文章:

java - 如何将 List<Object> 转换为 List<MyClass>

java - 将所有项目依赖项部署到远程存储库

java 生产者消费者问题-让线程等待其他线程完成后再完成

java - 优化JDBC中数据调用到JTable

java - 根据 JFrame 大小调整 JPanel 宽度

java - 限制对其他 JFrame 的访问

java - 如何修复使用 Mahout 在 SetFetchSize() 上失败的建议

java - JTable 与 JButton 作为单元格编辑器

java - Nimbus 外观和感觉 JTabbedPane 选项卡背景颜色

java - 如何从 JFrame 1 获取数据到另一个 JFrame?