我将JPanel设置为GridLayout(6,6),尺寸为(600,600)
网格的每个单元将显示一张具有不同宽度和高度的图片。
图片首先添加到JLabel,然后JLabel添加到单元格。
如何获取单元格中图片的坐标而不是单元格的坐标?到目前为止,即使在屏幕上以不同尺寸显示图片时,输出也给出这些高度和宽度相等的坐标。
例如
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]
最佳答案
您的图像是否以所需的尺寸显示?
我认同。
无论如何,从您的代码看起来可以做什么,我猜它得到的是标签的大小,而不是图标的大小。就像任何JComponent一样,JLabel实际上是Container实例。因此,它们的大小取决于约束。因此,在GridLayout中,JLabel将具有单元格的大小,而所包含的Icon将具有图像的大小。
因此,要获取图像尺寸,必须调用((JLabel) component).getIcon()
才能检索有效图像尺寸。
关于java - 如何获取Gridlayout的坐标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2446011/