我將我的JPanel設置爲GridLayout(6,6),尺寸爲(600,600) 網格中的每個單元格將顯示具有不同寬度和高度的一張圖片。 圖片首先添加到JLabel,然後將JLabel添加到單元格中。如何獲取Gridlayout的座標
如何檢索單元格中圖片的座標而不是單元格的座標?到目前爲止,即使在屏幕上,也給出了這些等高和寬相同的座標,不同大小的圖片顯示出來。
例如
java.awt.Rectangle[x=100,y=100,width=100,height=100]
java.awt.Rectangle[x=200,y=100,width=100,height=100]
java.awt.Rectangle[x=300,y=100,width=100,height=100]
我之所以用GridLayout代替gridBagLayout是因爲我希望每個圖片都有邊界。如果我使用GridBagLayout,網格將根據圖片大小進行擴展。 我希望網格大小處於固定大小。
JPanel pDraw = new JPanel(new GridLayout(6,6));
pDraw.setPreferredSize(new Dimension(600,600));
for (int i =0; i<(6*6); i++)
{
//get random number for height and width of the image
int x = rand.nextInt(40)+(50);
int y = rand.nextInt(40)+(50);
ImageIcon icon = createImageIcon("bird.jpg");
//rescale the image according to the size selected
Image img = icon.getImage().getScaledInstance(x,y,img.SCALE_SMOOTH);
icon.setImage(img);
JLabel label = new JLabel(icon);
pDraw.add(label);
}
for(Component component:components)
{
//retrieve the coordinate
System.out.println(component.getBounds());
}
編輯:我已經試過,但沒有工作:-(
for(Component component: pDraw.getComponents()){
System.out.println(((JLabel)component).getIcon());
}
我怎樣才能得到這樣的
java.awt.Rectangle[x=300,y=100,width=50,height=40]
java.awt.Rectangle[x=400,y=400,width=60,height=50]