如何在中心屏幕中定位表单? [英] How to position the form in the center screen?

查看:252
本文介绍了如何在中心屏幕中定位表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名.Net开发人员,但不知怎的,我的任务是在java中创建一个简单的应用程序,原因有些。我能够创建该应用程序,但我的问题是如何在应用程序启动时将窗体置于屏幕中心?

I'm a .Net developer but somehow I was task to create a simple application in java for some extra reason. I was able to create that application but my problem is how can i center the form in the screen when the application is launched?

这是我的代码:

private void formWindowActivated(java.awt.event.WindowEvent evt) 
{
        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

        // Move the window
        this.setLocation(x, y);
}

上面的代码工作正常,但问题是我看到表单正在移动从最顶部到中心屏幕。我还尝试在 formWindowOpened 事件中添加该代码,但仍显示相同的操作。有更好的方法吗?就像在 .NET Application 中一样,有一个 CenterScreen Position 。或者,如果上面的代码是正确的,我将把它放在什么事件上?

The code above works fine but the problem is I've seen the form moving from the topleft most to center screen. I also tried adding that code in formWindowOpened event and still shows same action. Is there a better way for this? Just like in .NET Application there is a CenterScreen Position. Or if the code above is correct, on what Event will i put it?

感谢您阅读本文。

推荐答案

在JFrame上调用pack之后,只需设置相对于null的位置即可。

Simply set location relative to null after calling pack on the JFrame, that's it.

例如,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);

这篇关于如何在中心屏幕中定位表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆