如何將圖像放置在單元格邊界內?如何在單元格邊界內顯示圖像
我的意思是沒有考慮到其他細胞的空間? 在下面的代碼中,選擇了隨機單元格來顯示圖像。一個單元格中的一個圖像。 問題是,圖像似乎也採取其他單元格。 alt text 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;
}
你想擁有相同尺寸的所有圖像嗎? – Jack 2010-03-08 01:34:42
不,我隨機縮放圖像並隨機選擇單元格。 – Jessy 2010-03-08 01:47:04