How to get the coordinate of Gridlayout

Posted by Jessy on Stack Overflow See other posts from Stack Overflow or by Jessy
Published on 2010-03-15T09:15:08Z Indexed on 2010/03/15 9:19 UTC
Read the original article Hit count: 416

Filed under:
|

Hi,

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

© Stack Overflow or respective owner

Related posts about java

Related posts about gridlayout