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条回答
Fickle 薄情
2楼-- · 2019-01-08 04:49

I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.

查看更多
等我变得足够好
3楼-- · 2019-01-08 04:53

You can use this method, which allows the JFrame to be centered and full screen at the same time.

yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
查看更多
男人必须洒脱
4楼-- · 2019-01-08 04:54

If you use NetBeans, simply click on the frame on the design view, then the code tab on its properties. Next, check 'Generate Center'. That will get the job done.

查看更多
Bombasti
5楼-- · 2019-01-08 04:55

I always did it in this way:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

where this is the JFrame involved.

查看更多
老娘就宠你
6楼-- · 2019-01-08 04:58

Just click on form and go to JFrame properties, then Code tab and check Generate Center.

enter image description here

查看更多
\"骚年 ilove
7楼-- · 2019-01-08 05:01

Use setLocationRelativeTo(null)

This method has a special effect when you pass it a null. According to the Javadoc:

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

This should be done after setting the size or calling pack(), but before setting it visible, like this:

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
查看更多
登录 后发表回答