开发者

How to get the coordinate of Gridlayout

开发者 https://www.devze.com 2022-12-23 11:00 出处:网络
I set my JPanel to GridLayout (6,6), with dimension (600,600) Each cell of the grid will display one pictures with different widths and heights.

I set my JPanel to GridLayout (6,6), with dimension (600,600) Each cell of the grid will display one pictures with different widths and heights. The picture first add to a JLabel, and the JLabel then added to the cells.

How can retrieved the coordinate of the pictures in the cells and not the coordinate of cells? So far the out give these coordinate which equal height and width even on screen the pictures showed in different sizes.

e.g.

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]

开发者_如何学运维The reason why I used GridLayout instead of gridBagLayout is that, I want each pictures to have boundary. If I use GridBagLayout, the grid will expand according to the picture size. I want grid size to be in fix size.

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());
}

EDITED: I have tried this but not working :-(

for(Component component: pDraw.getComponents()){
  System.out.println(((JLabel)component).getIcon());
}

How can I get output like these?

java.awt.Rectangle[x=300,y=100,width=50,height=40]
java.awt.Rectangle[x=400,y=400,width=60,height=50]


Do your images appear at the desired size ?

i think so.

Anyway, from what your code seems to do, I guess it gets the labels size, and not the icons size. JLabel, like any JComponent, are in fact Container instance. As such, their size depends upon constraints. As a consequence, in a GridLayout, a JLabel will have the size of a cell, whereas the contained Icon will have the size of the image.

As a consquence, to get image size, you have to call ((JLabel) component).getIcon() to be able to retrieve effective image dimension.

0

精彩评论

暂无评论...
验证码 换一张
取 消