首页 > 解决方案 > BoxLayout can't be shared 错误,试图在一个 JFrame 中容纳两个 JPanel

问题描述

试图在一个框架中放置 2 个面板,一个小的面板在顶部,一个填充框架的其余部分。但是,此代码返回“无法共享 BoxLayout”错误。

        JFrame frame = new JFrame("Clients");
        frame.setSize(1000,900);

        JPanel sorters = new JPanel();
        sorters.setSize(1000, 100);
        frame.getContentPane().add(sorters);

        JPanel rowPane = new JPanel();
        JScrollPane scrPane = new JScrollPane(rowPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrPane.setSize(1000, 800);
        frame.getContentPane().add(scrPane);

        frame.getContentPane().setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));

标签: javaswingjframejpanel

解决方案


ABoxLayout必须将其应用到的实际容器作为第一个参数,在您的情况下,容器是 frame 的 contentPane:

frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

推荐阅读