JFrame center combined with package ()

I am trying to focus on JFrame

which I used for pack()

and I got it, but I think this is not the clean path . This is how I do it 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);

      

I box it after filling to get the final one PreferredSizes

, so I can use those values ​​in the method setBounds

. But I don't like restoring it after packaging.

Any better ideas?

+3


source to share


1 answer


To center the window on the screen, you need to call window.setLocationRelativeTo(null)

immediately after pack () and before making your window visible:

JFrame window = new JFrame();
...

window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);

      

By Window # setLocationRelativeTo (component c) docs:

public void setLocationRelativeTo(Component c)

      

Sets the position of the window relative to the specified component according to the following scenarios.

The target screen mentioned below is the screen to which the window should be placed after the method call setLocationRelativeTo

.

  • If a component is null

    or a related GraphicsConfiguration

    component null

    , the window is placed in the center of the screen. The center point can be obtained with GraphicsEnvironment.getCenterPoint

    .



On the other hand

Some developers may advise you to use Window # setLocationByPlatform (a boolean flag) instead setLocationRelativeTo(...)

to honor the default location for the native windowing system of the platform that the desktop application is running on. This makes sense since your application must be designed to run on different platforms with different windowing systems and PLAFs .

+7


source







All Articles