You need to call frame.pack()
to do the initial layout. Resizing the window automatically causes the layout to be fixed, but frame.setSize(...)
does not*.
Move frame.setVisible(true)
to the end of your run
method (i.e. after you’ve constructed all the UI elements) and put frame.pack()
just before frame.setVisible(true)
. (Thanks Hovercraft and MadProgrammer for pointing this out)
*At least, it doesn’t if the frame is not visible. It might work if the frame is already visible; try it and see.
EDIT: Now that I re-read the javadoc, you probably don’t want pack
after all – it will resize the frame for you. Without testing it, I guess that moving setVisible
to the end will work; if it doesn’t then use revalidate
rather than pack
to get the layout engine to run.
EDIT 2: Now that I re-re-read the javadoc, setVisible
will validate the window if it is not already displayable. So you won’t need an explicit call to revalidate
. setSize
will invalidate the component but will not revalidate it.
TL;DR: It’s worth reading up on how validation and displayability work in Swing so you don’t make the mistakes I just did.