我在学校作业上遇到了一些麻烦。注释显示了讲师给出的伪代码。出于某种原因,我一直收到这个错误:
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));
资源:
- BoxLayout API
- 相关教程