How to set JFrame to appear centered, regardless o

2019-01-08 04:14发布

While working with Java, I find it hard to position my main window in the center of the screen when I start the application.

Is there any way I can do that? It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.

11条回答
虎瘦雄心在
2楼-- · 2019-01-08 05:01

If you explicitly setPreferredSize(new Dimension(X, Y)); then it is better to use:

setLocation(dim.width/2-this.getPreferredSize().width/2, dim.height/2-this.getPreferredSize().height/2);

查看更多
干净又极端
3楼-- · 2019-01-08 05:03

i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.

in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'. you will need first to set the Form Size Policy to 'Generate Resize Code'.

查看更多
Juvenile、少年°
4楼-- · 2019-01-08 05:04

You can call JFrame.setLocationRelativeTo(null) to center the window. Make sure to put this before JFrame.setVisible(true)

查看更多
小情绪 Triste *
5楼-- · 2019-01-08 05:13

As simple as this...

setSize(220, 400);
setLocationRelativeTo(null);  

or if you are using a frame then set the frame to

frame.setSize(220, 400);
frame.setLocationRelativeTo(null);  

For clarification, from the docs:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

查看更多
劫难
6楼-- · 2019-01-08 05:15

You'll get the size set, after you add this:

frame.setLocationRelativeTo(null);

查看更多
登录 后发表回答