I'm trying to center a JFrame
i used to pack()
, and I got it, but I think it's not the clean way.
This is how I'm doing 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 pack it after filling it to get the final PreferredSizes
, so I can use those values in the setBounds
method. But I don't like rebounding it after packing it.
Any better ideas?
To center a window in the screen you need to call window.setLocationRelativeTo(null)
right after pack() call and before making your window visible:
JFrame window = new JFrame();
...
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
As per Window#setLocationRelativeTo(Component c) docs:
public void setLocationRelativeTo(Component c)
Sets the location of the window relative to the specified component according to the following scenarios.
The target screen mentioned below is a screen to which the window should be placed after the
setLocationRelativeTo
method is called.
- If the component is
null
, or theGraphicsConfiguration
associated with this component isnull
, the window is placed in the center of the screen. The center point can be obtained with theGraphicsEnvironment.getCenterPoint
method.
Some developers might advice you to use Window#setLocationByPlatform(boolean flag) instead of setLocationRelativeTo(...)
in order to honor the default location for the native windowing system of the platform where your desktop application is running. This makes sense since your application must be designed to run in different platforms with different windowing systems and PLAFs.