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 yourWindow.pack()
to perform the layout.
Altho very uncommon, call yourWindow.revalidate()
to redo the layout
if the size of one of the components changes. If you're doing this, perhaps
you should rethink the interface design.
The following code positions a window (JFrame) f in the center of the screen.
Use this when you create a window, after yourWindow.pack()
has been called, as follows:
window.setLocationRelativeTo(null);
To make a window fill the screen or take a percentage of the screen size, use something like the following.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); window.setSize(screenSize.width, screenSize.height); window.validate(); // Make sure layout is ok
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()
.
However, if you must create a fixed size window (JFrame), call
f.setSize(...)
, then call
f.validate()
to finalize the component layout before making the window
visible.