title: Why do you need to invoke setLayout with BoxLayout?
body: <p>Most layout managers have no-argument constructors (that is, you can create a FlowLayout with <code>new FlowLayout ()</code>, a GridLayout with <code>new GridLayout ()</code>, a GridBagLayout with <code>new GridBagLayout ()</code>, etc.). However, <code>BoxLayout</code> requires that you pass both the container that it will be managing and the axis along which the components should be laid out.</p>
  
  <p>My question is: since you're already telling the layout manager which component to lay out, why do you need to write</p>
  
  <pre><code>BoxLayout bl = new BoxLayout(myPanel, BoxLayout.Y_AXIS);
  myPanel.setLayout(bl);
  </code></pre>
  
  <p>instead of just the first line?</p>
  
  <p>I took a quick look at <a href="http://www.docjar.com/html/api/javax/swing/BoxLayout.java.html" rel="noreferrer">the <code>BoxLayout</code> source code</a> and saw that the constructor I use (lines 178-185) doesn't make a call to <code>target.setLayout(this)</code> or anything of the sort. It seems like it would be really simple to just add that. Is there a reason why it's not included in the Swing library?</p>
  
  <p>If it matters, I'm using</p>
  
  <blockquote>
    <p>java version 1.7.0</p>
    
    <p>Java(TM) SE Runtime Environment (build 1.7.0-b147)</p>
  </blockquote>
  
  <p>on Win7Pro.</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>SSCCE:</p>
  
  <pre><code>import javax.swing.JFrame;
  import javax.swing.JPanel;
  import javax.swing.JButton;
  
  public class BoxLayoutSSCCE extends JFrame {
  
      // Change this to see what I mean
      public static final boolean CALL_SET_LAYOUT = true;
  
      public BoxLayoutSSCCE () {
          super("Box Layout SSCCE");
          JPanel panel = new JPanel();
          BoxLayout bl = new BoxLayout(panel, BoxLayout.Y_AXIS);
          if (CALL_SET_LAYOUT) {
              panel.setLayout(bl);
          }
          panel.add(new JButton("Button 1"));
          panel.add(new JButton("Button 2"));
      }
  
      public static void main (String[] args) {
          BoxLayoutSSCCE blsscce = new BoxLayoutSSCCE();
          blsscce.pack();
          blsscce.setVisible(true);
      }
  }
  </code></pre>