【问题标题】:Center JFrame in combination with pack()中心 JFrame 结合 pack()
【发布时间】:2014-10-26 18:43:46
【问题描述】:

我正在尝试使 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 方法中使用这些值。但我不喜欢打包后反弹。

有更好的想法吗?

【问题讨论】:

标签: java swing jframe window pack


【解决方案1】:

要在屏幕中居中窗口,您需要在 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(...),以便遵循运行桌面应用程序的平台的本机窗口系统的默认位置。这是有道理的,因为您的应用程序必须设计为在具有不同窗口系统和PLAFs 的不同平台上运行。

【讨论】:

  • 我不知道“null”是“屏幕中间”的同义词;)非常感谢,这就是我要找的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多