由于 JPanel 未调整大小,JScrollPane 没有反应

JScrollPane not reacting due to JPanel not resizing

我有一个cardlayout JPanel,里面是一个JScrollPane,里面是一个springlayout JPanel。 springlayout JPanel 正在从上到下动态添加 JPanels,但是当 JButtons 超出 JPanel 时,JScrollPane 无法容纳额外的内容。此外,尽管添加了内容,但显然 springlayout JPanel 的高度仍然为 0。设置可调整大小 属性 true 也无济于事。

这是一段代码。我省略了卡片布局 JPanel 和切换卡片的代码。

    SpringLayout mainlayout = new SpringLayout();
    JPanel maincard = new JPanel(mainlayout); // springlayout JPanel
    for (int i = 0; i < info.size(); i++) {
        GridLayout entryLayout = new GridLayout(1, 1);
        JPanel entry = new JPanel(entryLayout);
        entry.setSize(800, 30);

        JButton name = new JButton();
        name.setSize(250, 30);
        name.setText(info.get(i).name);

        entry.add(name);

        mainlayout.putConstraint(SpringLayout.NORTH, entry,
                 i * 100 + 5,
                 SpringLayout.NORTH, maincard); // moves JPanel lower and lower
        maincard.add(entry);
    }
    maincard.setSize(width, 30 * (info.size() + 1));
    maincard.revalidate();
    JScrollPane scroll = new JScrollPane(maincard);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setSize(200, 200); // this and setPreferredSize don't affect
    cardpanel.add(scroll, cardName);
    cardpanel.setSize(20, 200); // no effect

我自己也遇到过一些问题。对我有用的是使用边框布局。并且您需要在添加新元素后调用 revalidate 以更新滚动面板。

这是我不久前在我的项目中使用的代码示例:

public BookingTable()
{
    super(new BorderLayout());
    _contentPanel = new JPanel();
    _contentPanel.setLayout(new BoxLayout(_contentPanel, BoxLayout.Y_AXIS));
    _scrollPane = new JScrollPane(_contentPanel);

    add(_scrollPane, BorderLayout.CENTER);
}

private void addToPanel(EntryView panel)
{
    panel.setPreferredSize(new Dimension(150, 35));
    panel.setMaximumSize(new Dimension(160, 45));
    panel.setMinimumSize((new Dimension(80, 30)));   

    _contentPanel.add(panel);
    _contentPanel.revalidate();
}

希望对您有所帮助!另一个提示是,如果您从 Scrollpane 中删除元素,您需要调用 Repaint 以便实际从 UI 中删除元素,如果您不这样做,它们将保持可见,直到您绘制它们。