You do want to use a GridLayout
. Your problem is that the JFrame
you put the icons into uses a BorderLayout
by default (and really, you shouldn't change the layout of a top level component).
What this means is that, if you add multiple panels to the frame, without using one of the NORTH
, EAST
, SOUTH
, WEST
constraints, only one of the panels will be visible and take up all the space. If you use a GridLayout
for that one panel you get, the icons will be stretched, because the panel receives all the space due to the frame's BorderLayout
. An alternate layout that doesn't stretch its contents is FlowLayout
, but the layout to use depends heavily on your context.
To display the icons, a JLabel
is handy. Use an ImageIcon
for the label's icon. You can later use setIcon()
on the label to choose a new icon.
overall, my approach would be this:
- use a
JFrame
which has aBorderLayout
- to the frame, add a
JPanel
to the frame. The default layout is aFlowLayout
, which will prevent the stretching - to the panel, add a
JPanel
with an appropriateGridLayout
- to that panel, add the
JLabel
s, each having an appropriateImageIcon