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
}
Add your
JPanelto theJFrames contentPane thus allowing you to get the X and Y co ordinates usinggetX()andget()though I’d suggest adding all components first, as the points may change as more components are added and then as trashgod said simply callpack()on the frame instance.I did a short sample to demonstrate:
As you can see calling
printPanelCompPoints(mainPanel);ininitComponents(JFrame frame)produces all 0’s, (as they have been added to the frame but `pack() has not been called).however in the
createAndShowUI()after callingpack()on theJFrames instance callingprintPanelCompPoints(mainPanel);produces the correct co-odrinates: