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
Pack the frame before getting position. It seems everything overlaps each other starting at origin (0,0) until you pack.
Here's a working code:
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestBoxLayout {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panelHolder = new JPanel();
panelHolder.setLayout(new BoxLayout(panelHolder, BoxLayout.Y_AXIS));
for (int i = 0; i < 10; i++) {
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(100, 13)); //I set the height just to make sure.
panelHolder.add(p);
}
frame.add(panelHolder);
/**
* Pack before you get the position.
*/
frame.pack();
int componentCount = panelHolder.getComponentCount();
for (int j = 0; j < componentCount; j++) {
Component c = panelHolder.getComponent(j);
JPanel p = (JPanel) c;
System.out.println(p.getY());//I get 0, 13, 26, 39, .....
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Result:
0
13
26
39
52
65
78
91
104
117
Note: The signature for BoxLayout is BoxLayout(Container target, int axis)
. The target
is the stuff you are setting your layout to. For this reason, if you want use a BoxLayout, you should always create the panel first. Then use component.setLayout()
so that the target already exists. The this
in your JPanel constructor was referring to something else, not panelHolder
. I guess the class you created this function in is also a subclass of Container
and that is why you didn't get an error.