0

I am having some trouble with an assignment for school. The comments show the pseudocode given by the instructor. For some reason, I keep getting this error:

java.awt.AWTError: BoxLayout can't be shared

Here is my code:

    // Declare and create a JPanel named panelMain. Use the horizontal BoxLayout layout manager.
    // Add some vertical glue to panelMain (using Box.createVerticalGlue()). Add panelLabel.
    // Add some more vertical glue. Add panelTextField. Add panelBottom. Add some more vertical
    // glue.

    JPanel panelMain = new JPanel();


    panelMain.setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

    Box.createVerticalGlue();


    panelMain.add(panelLabel); //Error happens from here on
    panelMain.add(createVerticalGlue());
    panelMain.add(panelTextField);
    panelMain.add(panelBottom);
    panelMain.add(createVerticalGlue());
Jonathan Zier
  • 150
  • 2
  • 14

1 Answers1

1

Here:

panelMain.setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

You need the container that is getting the layout, panelMain, to be the same as the one within the BoxLayout constructor, not getContentPane(). So the correct code would be:

panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.X_AXIS));

Resources: