不断获取java.awt.AWTError:无法共享BoxLayout

时间:2018-11-01 20:35:38

标签: java swing boxlayout

我在做作业时遇到麻烦。注释显示了教师给出的伪代码。由于某些原因,我一直收到此错误:

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

1 个答案:

答案 0 :(得分:1)

这里:

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

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

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

资源: