Java Notes: Window Size and Position
First pack your window to do the layout
The optimum size of a window depends on the size and layout of the components.
After adding all the components to a window (JFrame), call pack()
to perform the layout.
Centering a Window
The following code positions a window (JFrame) f in the center of the screen.
Use this when you create a window, after calling pack()
has been called, as follows.
setLocationRelativeTo(null); // Implicit "this" if inside JFrame constructor.
f.setLocationRelativeTo(null); // Explicit JFrame if outside JFrame constructor.
NetBeans. In the GUI Editor (Matisse) generated source code, add the following statement to the constructor that is automatically generated.
public SortDemoGUI() { // Matisse generated constructor for SortDemoGUI class.
initComponents(); // Matisse generated call to initialization method.
setLocationRelativeTo(null); // Add this line to center JFrame.
}
You can use the older, more explicit, way of centering a window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = window.getSize(); int windowX = Math.max(0, (screenSize.width - windowSize.width ) / 2); int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2); f.setLocation(windowX, windowY); // Don't use "f." inside constructor.
The Math.max
call makes sure the window origin is not negative.
Expanding a window to fit the screen
The first example leaves a 4 pixel border around the window. The second example passes the Dimension object directly to setSize(). You don't need the explicit "f." if this code is in the constructor.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); f.setSize(screenSize.width - 4, screenSize.height - 4); f.validate(); // Make sure layout is ok
Completely full screen.
f.setSize(Toolkit.getDefaultToolkit().getScreenSize()); f.validate(); // Make sure layout is ok
Fixed Window Size using setSize() and validate() - Probably a mistake
You can set the size of a window, but it's almost always
a mistake unless you're simply expanding the window to fill the screen.
The default window size should depend on the size
and layout of the components as determined by pack()
.
If you must create a fixed size window (JFrame), call
setSize(width, height)
or setSize(dimension)
, then call
validate()
to finalize the component layout before making the window
visible.