How can I place an image within the cell boundary?
I mean without taking the space of other cell? In the code below, random cells were selected to display images. One image in one cell. The problem is that, the image seems to take other cells as well.
...
setPreferredSize(new Dimension(600,600));
final int ROWS = 6;
final int COLS = 6;
final int IMAGES = 10;
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1d;
gc.weighty = 1d;
gc.insets = new Insets(0, 0, 0, 0);//top, left, bottom, and right
gc.fill = GridBagConstraints.NONE;
JLabel[][] label = new JLabel[ROWS][COLS];
Random rand = new Random();
// fill the panel with labels
for (int i=0;i<IMAGES;i++){
ImageIcon icon = createImageIcon("myImage.jpg");
int r, c;
do{
//pick random cell which is empty to avoid overlap image in the same cell
r = (int)Math.floor(Math.random() * ROWS);
c = (int)Math.floor(Math.random() * COLS);
} while (label[r][c]!=null);
//scale the image
int x = rand.nextInt(20)+30;
int y = rand.nextInt(20)+30;
Image image = icon.getImage().getScaledInstance(x,y, Image.SCALE_SMOOTH);
icon.setImage(image);
JLabel lbl = new JLabel(icon);
gc.gridx = r;
gc.gridy = c;
add(lbl, gc); //add image to the cell
label[r][c] = lbl;
}