views:

67

answers:

2

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. alt text

...
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; 
}
+2  A: 

What kind of question is this? You have about 5 questions on the same topic. The random code you posted is useless unless people have read all 4 previous questions and have some idea of what you are doing. I know I've read them and still don't understand.

Cells don't have a boundary. When you add a component to a cell, then the cell will be the size of the component you add. Since you only have a few occupied cells, then most of your cells have no actual size.

So presumably if you want to a a new component to an unoccupied cell, at position (3, 4) for example, the I guess you would need to look at all the cells on row 3 to determine the maximum height for that row. Then you would need to look at all the cells in column 4 to determine the maximum width. Combine the two and you have the size of the cell.

You already know how to get the constraints, so you should be able to figure out the rest.

Then again, I probably have no idea what you are doing and therefore my answer is just one big ramble.

If you need more help post your SSCCE.

camickr
+1  A: 

Recalling your recent question regarding essentially the same code, try adding your ImageIcon to the JLabel in this example.

trashgod