Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get location of a swing component

I have put some JPanels into another JPanel which its' layout is Box Layout and Y-Axis. After I have put all the panels I need to get the Y position of each added JPanel in from the JPanel container panel. But, when I try to get that I always get zero for Y position of each JPanel. Please tell me how to get the Y position of each Jpanel from the JPanel container JPanel.

This is what I have done,

JPanel panelHolder = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS));
for(int i = 0; i< 10; i++){
   JPanel p = new JPanel(); 
   panelHolder.add(p);
}

int componentCount = panelHolder.getComponentCount();

for (int j = 0; i < componentCount ; j++) {

  Component c = pnlRowHolder.getComponent(i);
  JPanel p = (JPanel)c;
  System.out.println(p.getY());//I get zero for all
}
like image 496
Harsha Avatar asked Sep 25 '12 19:09

Harsha


1 Answers

Coordinates are relative to their parent. In your exemple, all the child components are being added along the top of the parent container, making there y position 0 (relative to their parent).

Try adding an empty border to the parent container, you should see the y position change.

You can use the SwingUtilities.convertPoint to convert between coordinate systems

like image 53
MadProgrammer Avatar answered Sep 21 '22 14:09

MadProgrammer