【问题标题】:error upon assigning Layout: BoxLayout can't be shared分配布局时出错:无法共享 BoxLayout
【发布时间】:2010-10-20 04:00:47
【问题描述】:

我有这个 Java JFrame 类,我想在其中使用 boxlayout,但我收到一条错误消息 java.awt.AWTError: BoxLayout can't be shared。我见过其他人有这个问题,但他们通过在内容窗格上创建 boxlayout 来解决它,但这就是我在这里所做的。这是我的代码:

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);
    }
}

【问题讨论】:

    标签: java swing layout boxlayout


    【解决方案1】:

    您的问题是您正在为JFrame (this) 创建一个BoxLayout,但将其设置为JPanel (getContentPane()) 的布局。试试:

    getContentPane().setLayout(
        new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)
    );
    

    【讨论】:

    • 是的,但是删除它会混淆问题,现在不是吗?
    【解决方案2】:

    我也发现了这个错误:

    JPanel panel = new JPanel(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    

    将 JPanel 传递给 BoxLayout 时,它尚未初始化。所以像这样分割这一行:

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    

    这会起作用。

    【讨论】:

      【解决方案3】:

      我认为从前面的答案中强调的一个重要的事情是 BoxLayout 的目标(第一个参数)应该是调用 setLayout 方法的同一个容器,如下例所示:

      JPanel XXXXXXXXX = new JPanel();
      XXXXXXXXX.setLayout(new BoxLayout(XXXXXXXXX, BoxLayout.Y_AXIS));
      

      【讨论】:

        【解决方案4】:

        如果您在 JFrame 上使用布局,例如:

        JFrame frame = new JFrame();
        frame.setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));
        frame.add(new JLabel("Hello World!"));
        

        控件实际上已添加到ContentPane,因此它看起来像是在JFrameContentPane 之间“共享”

        改为这样做:

        JFrame frame = new JFrame();
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
        frame.add(new JLabel("Hello World!"));
        

        【讨论】:

        • 你救了我,为什么这是唯一提到 getContentPane() 的答案?
        • @AlexanderMcNulty,可能是因为JFrames 通常不需要它(与 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 中只有一个内容窗格,并且始终保证存在。
        猜你喜欢
        • 2014-12-25
        • 1970-01-01
        • 1970-01-01
        • 2019-04-06
        • 2015-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多