我将我的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]