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?
What you call JPanel.setLayout
is actually Container.setLayout:
public void setLayout(LayoutManager mgr)
You call call the method with a BoxLayout
because it implements LayoutManager
. But LayoutManager
does not have a setContainer
method, so it would not have worked without adding that method. But it seems that most layout managers don't care about a container so the method would not belong there.
Would it be possible for BoxLayout
constructor to do the magic? Maybe not, though a BoxLayout
is tied to a Container
, the reverse is not necessarily true. Consider:
this.cntnrPnl = new JPanel();
BoxLayout bY = new BoxLayout(this.cntnrPnl, BoxLayout.Y_AXIS);
BoxLayout bX = new BoxLayout(this.cntnrPnl, BoxLayout.X_AXIS);
Now at different times you can call this.cntnrPnl.setLayout(bX)
and this.cntnrPnl.setLayout(bY)
.
So looking at all options, it seems the current API is best, though of course all this is somewhat subjective.
By the way, please consider renaming cntnrPnl
to containerPanel
. You are not really saving much by stripping the vowels.