1

Trying to create a gridLayout and fill it with images, where is it going wrong?

ImageIcon grassIcon = new ImageIcon("images/grass_tile.jpg"); 
JPanel panel = new JPanel(new GridLayout(haps,snaps,0,0));

JLabel labels[] = new JLabel[(haps*snaps)];

for (int i =  0; i < haps*snaps; i++)
{
    labels[i] = new JLabel(grassIcon);
    panel.add(labels[i]);
}

frame.add(panel);
toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
  • 4
    what do you see ? error ? do you call frame.pack()? – ben75 Jan 28 '13 at 09:29
  • frame.pack() did the job! But how and why ? To the documentation!!! thanks. – Jesper Tuborg Madsen Jan 28 '13 at 09:32
  • @JesperTuborgMadsen : As to why it happened, **In Swing when you create Component, it is not valid i.e. it's valid property is false. A component is said to be valid, when it's width, height, location and stuff has been determined. This is usually done by calling their validate() method, directly or indirectly. When we call validate() on containers, it will validate the container (if it is invalid) by calling its doLayout() method, which typically will invoke the LayoutManager.** – nIcE cOw Jan 28 '13 at 13:11
  • Continued... : **Now each child placed on this container will be validated recursively, so that the entire tree will be laid out and will become valid.** Here calling `pack()` is indirectly changing the `invalid state` of the components to a `valid state`. More info can be found on this [thread](http://stackoverflow.com/q/9510125/1057230) – nIcE cOw Jan 28 '13 at 13:12

3 Answers3

1

Just try to check your image path if you have it correctly. Or maybe for a test if you can really make the image appear, try to make it an absolute path. And also, please elaborate your problems in there.

nsutgio
  • 240
  • 2
  • 6
  • 15
1

As ben75 writes, it needed frame.pack(); Creds to him!

1

Show the frame by using frame.setVisible(true);

ImageIcon grassIcon = new ImageIcon("images/grass_tile.jpg"); 
JPanel panel = new JPanel(new GridLayout(haps,snaps,0,0));

JLabel labels[] = new JLabel[(haps*snaps)];

for (int i =  0; i < haps*snaps; i++)
{
      labels[i] = new JLabel(grassIcon );
      panel.add(labels[i]);
}

frame.add(panel);
frame.pack();
frame.setVisible(true);
Alya'a Gamal
  • 5,624
  • 19
  • 34