Search code examples
javaswingjframeboxlayout

BoxLayout can't be shared using "createComponents" method


I'm having trouble running my code to create a simple survey. I'm just starting with UIs and BoxLayout is giving me an error: Exception in thread "AWT-EventQueue-0" java.awt.AWTError: BoxLayout can't be shared. Help?

import java.awt.Container;
import java.awt.Dimension;
import javax.swing.*;

public class UserInterface implements Runnable {

    private JFrame frame;

    @Override
    public void run() {
        frame = new JFrame("Survey");

        frame.setPreferredSize(new Dimension(200, 300));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        createComponents(frame);
        frame.pack();
        frame.setVisible(true);
    }

    private void createComponents(Container container) {
        BoxLayout bl = new BoxLayout(container, BoxLayout.Y_AXIS);
        container.setLayout(bl);

        container.add(new JLabel("Are you?"));
        container.add(new JCheckBox("Yes!"));
        container.add(new JCheckBox("No!"));
        container.add(new JLabel("Why?"));

        JRadioButton one = new JRadioButton("No reason.");
        JRadioButton two = new JRadioButton("Because it is fun!");

        ButtonGroup bg = new ButtonGroup();
        bg.add(one);
        bg.add(two);

        container.add(one);
        container.add(two);

        container.add(new JButton("Done!"));
    }

    public JFrame getFrame() {
        return frame;
    }
}

Solution

  • However, is there a way to keep these two methods separate?

    Easy: Simply pass the contentPane into the method.

    createComponents(frame.getContentPane());