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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With