error upon assigning Layout: BoxLayout can't be shared
我有这个Java JFrame类,我想在其中使用boxlayout,但是出现错误消息java.awt.AWTError: BoxLayout can't be shared。 我已经看到其他人遇到了这个问题,但是他们通过在contentpane上创建boxlayout来解决了这个问题,但这就是我在这里所做的。 这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12
| class EditDialog extends JFrame {
JTextField title = new JTextField();
public editDialog () {
setDefaultCloseOperation (JFrame. DISPOSE_ON_CLOSE);
setTitle ("New entity");
getContentPane (). setLayout(
new BoxLayout(this, BoxLayout. PAGE_AXIS));
add (title );
pack ();
setVisible (true);
}
} |
您的问题是您正在为JFrame(this)创建BoxLayout,但是将其设置为JPanel(getContentPane())的布局。 尝试:
我也发现了这个错误:
将JPanel传递到BoxLayout时尚未初始化。 所以像这样分割这行:
这将起作用。
我认为从前面的答案中要强调的一件重要事情是BoxLayout的目标(第一个参数)应该与调用setLayout方法的容器相同,如以下示例所示:
如果您在JFrame上使用布局,例如:
该控件实际上已添加到ContentPane中,因此它看起来像是在JFrame和ContentPane之间"共享"的
改为这样做:
-
当你救了我,-为什么这是唯一提到getContentPane()的答案?
-
@AlexanderMcNulty,可能是因为JFrame通常不需要它(与AWT Frame不同)。 从JFrame文档中:As a convenience, the add, remove, and setLayout methods of this class are overridden, so that they delegate calls to the corresponding methods of the ContentPane. For example, you can add a child component to a frame as follows: frame.add(child); And the child will be added to the contentPane. The content pane will always be non-null.通过Frame指的是JFrame实例。
-
@AlexanderMcNulty,此外,JFrame中只有一个内容窗格,并且始终保证在那里。