分配布局时出错:BoxLayout 无法共享
我有一个 Java JFrame
类,我想在其中使用 boxlayout,但收到一条错误消息 java.awt.AWTError: BoxLayout can't be share
。 我见过其他人遇到这个问题,但他们通过在内容窗格上创建框布局来解决它,但这就是我在这里所做的。 这是我的代码:
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);
}
}
I have this Java JFrame
class, in which I want to use a boxlayout, but I get an error saying java.awt.AWTError: BoxLayout can't be shared
. I've seen others with this problem, but they solved it by creating the boxlayout on the contentpane, but that is what I'm doing here. Here's my code:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的问题是您正在为
JFrame
(this
)创建BoxLayout
,但将其设置为JPanel 的布局
(getContentPane()
)。 尝试:Your problem is that you're creating a
BoxLayout
for aJFrame
(this
), but setting it as the layout for aJPanel
(getContentPane()
). Try:我还发现了这个错误:
将 JPanel 传递给 BoxLayout 时尚未初始化。 所以像这样分割这一行:
这会起作用。
I've also found this error making this:
The JPanel isn't initialized yet when passing it to the BoxLayout. So split this line like this:
This will work.
我认为前面的答案中需要强调的一件重要事情是 BoxLayout 的目标(第一个参数)应该与调用 setLayout 方法的容器相同,如下例所示:
I think that one important thing to highlight from the previous answers is that the BoxLayout's target (the first parameter) should be the same Container that the setLayout method is being called upon as in the following example:
如果您在
JFrame
上使用布局,例如:该控件实际上被添加到
ContentPane
中,因此它看起来像是在JFrame 之间“共享”
和ContentPane
执行此操作:
If you're using the layout on a
JFrame
like:The control is actually being added to the
ContentPane
so it will look like it's 'shared' between theJFrame
and theContentPane
Do this instead: