无法使用 "createComponents" 方法共享 BoxLayout

BoxLayout can't be shared using "createComponents" method

我在创建简单调查的代码中遇到了问题 运行。我刚开始使用 UI,BoxLayout 给我一个错误:线程 "AWT-EventQueue-0" java.awt.AWTError 中的异常:无法共享 BoxLayout。帮忙?

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;
    }
}

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

简单:只需将 contentPane 传递到方法中即可。

createComponents(frame.getContentPane());