Can anybody explain why circular reference is being set twice in the followig code?
//declare panel
this.cntnrPnl = new JPanel();
//define layout manager for the panel - but why circ ref?
this.cntnrPnl.setLayout(new BoxLayout(this.cntnrPnl, BoxLayout.Y_AXIS));
Why is it necessary to link the BoxLayout back to the JPanel container explicitly instead of JPanel.setLayout doing the setting itself behind the scene and using a setter from BoxLayout for code compactness?
E.g.:
this.cntnrPnl.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
//and then in JPanel.setLayout have something line
_layout.setContainer(this);
Because BoxLayout is a special layout that needs a reference to the target container it lays out. That’s not the case of all the layout managers. It would be ugly to add a specific case for BoxLayout in the
setLayout()method. And it would also mean that the BoxLayout would be in an unstable state after its construction, since it wouldn’t have the mandatory target container yet.The reverse could have been done though: having the BoxLayout constructor call
setLayout(this)on the target container. But I don’t know why it hasn’t been done.