0

如何在单元格边界内放置图像?

我的意思是不占用其他单元格的空间?在下面的代码中,随机选择了单元格来显示图像。一个单元格中的一个图像。问题是,图像似乎也占用了其他单元格。 替代文字 http://www.freeimagehosting.net/image.php?9f84119a63.jpg

...
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; 
}
4

2 回答 2

2

这是个什么样的问题?您对同一主题有大约 5 个问题。你发布的随机代码是没有用的,除非人们已经阅读了之前的所有 4 个问题并且对你在做什么有所了解。我知道我已经阅读了它们,但仍然不明白。

单元格没有边界。当您将组件添加到单元格时,单元格将是您添加的组件的大小。由于您只有几个被占用的单元格,因此您的大多数单元格都没有实际大小。

因此,大概如果您想将新组件添加到未占用的单元格,例如位置 (3, 4),我想您需要查看第 3 行上的所有单元格以确定该行的最大高度。然后您需要查看第 4 列中的所有单元格以确定最大宽度。将两者结合起来,您就有了单元格的大小。

您已经知道如何获得约束,因此您应该能够弄清楚其余的。

再说一次,我可能不知道你在做什么,因此我的回答只是一个大杂烩。

如果您需要更多帮助,请发布您的SSCCE

于 2010-03-08T03:13:35.840 回答
1

回顾您最近关于基本相同代码的问题,尝试将您添加ImageIconJLabelin this example中。

于 2010-03-08T03:22:07.560 回答