无法使用"createComponents"方法共享框布局



我在运行代码创建简单调查时遇到问题。我刚从UI开始,BoxLayout给了我一个错误:线程"AWT-EventQueue-0"java.AWT.AWTWError: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;
    }
}

然而,有没有办法将这两种方法分开?

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

createComponents(frame.getContentPane());

相关内容

  • 没有找到相关文章

最新更新