Question

What is the best way to display let's say rectangle (3x5) with icons 20x20 px.? I want to change the image file of every pic icon later (= it's not just static pictures). I tried to make JFrame full of JPanels, but i was able to display only one panel at a time. I don't want to use GridLayout, because I need just small rectangle inside a frame. Any ideas how to do it? Couldn't find any tutorial or solution. I'm completely new to GUI developement. Thanks

Was it helpful?

Solution

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 a BorderLayout
  • to the frame, add a JPanel to the frame. The default layout is a FlowLayout, which will prevent the stretching
  • to the panel, add a JPanel with an appropriate GridLayout
  • to that panel, add the JLabels, each having an appropriate ImageIcon
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top