加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 中心JFrame与pack()的组合

发布时间:2020-12-15 04:22:09 所属栏目:Java 来源:网络整理
导读:我正试图将我曾经用过的JFrame作为打包(),我得到了它,但我认为这不是干净的方式. 这就是我在做atm的方式: JFrame window = new JFrame();//filling//window//with//stuffwindow.pack();Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();int x
我正试图将我曾经用过的JFrame作为打包(),我得到了它,但我认为这不是干净的方式.
这就是我在做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)文档:

06001

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(…),以便尊重运行桌面应用程序的平台的本机窗口系统的默认位置.这是有道理的,因为您的应用程序必须设计为在具有不同窗口系统和PLAF的不同平台上运行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读