Java BoxLayout 无法共享错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/761341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BoxLayout can't be shared error
提问by
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:
我有这个 JavaJFrame
类,我想在其中使用 boxlayout,但是我收到一条错误消息,说java.awt.AWTError: BoxLayout can't be shared
. 我见过其他人有这个问题,但他们通过在内容窗格上创建 boxlayout 解决了这个问题,但这就是我在这里做的。这是我的代码:
class edit_dialog extends javax.swing.JFrame{
javax.swing.JTextField title = new javax.swing.JTextField();
public edit_dialog(){
setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
setTitle("New entity");
getContentPane().setLayout(
new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));
add(title);
pack();
setVisible(true);
}
}
采纳答案by Michael Myers
Your problem is that you're creating a BoxLayout
for a JFrame
(this
), but setting it as the layout for a JPanel
(getContentPane()
). Try:
您的问题是您正在BoxLayout
为JFrame
( this
)创建 a ,但将其设置为JPanel
( getContentPane()
)的布局。尝试:
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)
);
回答by Joaquín M
I've also found this error making this:
我还发现了这个错误:
JPanel panel = new JPanel(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
The JPanel isn't initialized yet when passing it to the BoxLayout. So split this line like this:
在将 JPanel 传递给 BoxLayout 时,它尚未初始化。所以像这样拆分这条线:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
This will work.
这将起作用。
回答by diadyne
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:
我认为从前面的答案中要强调的一件重要事情是 BoxLayout 的目标(第一个参数)应该与调用 setLayout 方法的容器相同,如下例所示:
JPanel XXXXXXXXX = new JPanel();
XXXXXXXXX.setLayout(new BoxLayout(XXXXXXXXX, BoxLayout.Y_AXIS));
回答by Charlie
If you're using the layout on a JFrame
like:
如果您在JFrame
类似的情况下使用布局:
JFrame frame = new JFrame();
frame.setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));
frame.add(new JLabel("Hello World!"));
The control is actually being added to the ContentPane
so it will look like it's 'shared' between the JFrame
and the ContentPane
控件实际上被添加到了,ContentPane
所以它看起来像是在JFrame
和之间“共享”ContentPane
Do this instead:
改为这样做:
JFrame frame = new JFrame();
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.add(new JLabel("Hello World!"));