我是一名 .Net 开发人员,但不知何故,我的任务是在 java 中创建一个简单的应用程序,因为一些额外的原因。我能够创建该应用程序,但我的问题是如何在应用程序启动时将表单置于屏幕中心?
这是我的代码:
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
。或者如果上面的代码是正确的,我会把它放在什么事件上?
感谢您阅读本文。
最佳答案
在 JFrame 上调用 pack 后只需设置相对于 null 的位置即可。
例如,
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);
关于java - 如何将表格定位在中央屏幕中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9543320/