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

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

我在学校作业上遇到了一些问题。注释显示了指导者给出的伪代码。出于某种原因,我不断收到此错误:

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

这是我的代码:

    // 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());

这里:

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

您需要获取布局的容器 panelMain 与 BoxLayout 构造函数中的容器相同,而不是 getContentPane()。所以正确的代码是:

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

资源: