我在做作业时遇到麻烦。注释显示了教师给出的伪代码。由于某些原因,我一直收到此错误:
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());
答案 0 :(得分:1)
这里:
panelMain.setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
您需要用于获取布局的容器panelMain与BoxLayout构造函数中的容器相同,而不是getContentPane()
。因此正确的代码将是:
panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.X_AXIS));
资源: