【问题标题】:JScrollPane not reacting due to JPanel not resizing由于 JPanel 未调整大小,JScrollPane 没有反应
【发布时间】:2017-05-09 13:29:40
【问题描述】:

我有一个cardlayout JPanel,里面是一个JScrollPane,里面是一个springlayout JPanel。 springlayout JPanel 是与 JPanel 从上到下动态添加的,但是当 JButtons 超出 JPanel 时,JScrollPane 不会容纳额外的内容。此外,尽管添加了内容,但显然 springlayout JPanel 的高度仍然为 0。将 resizable 属性设置为 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

【问题讨论】:

  • apparently the springlayout JPanel's height remains 0 - SpringLayout 是使用起来比较复杂的布局管理器之一,因为它需要所有的约束。我的建议是使用另一个布局管理器。或者,如果您真的想使用 SpringLayout,那么您需要阅读 How to Use SpringLayout 上的 Swing 教程中的部分以获取更多信息和工作示例。本教程还包含有关其他标准布局管理器的部分。
  • 是的,我忘了提到我也尝试过其他布局。预期的输出应该类似于联系人列表,条目是 JPanel。我试过 GridLayout,但我无法控制条目的大小。对于 Box/BoxLayout,条目永远不会超出容器(网格布局也是如此)。 GridBagLayout 也有同样的问题。边框是不可能的(我不需要它来覆盖),并且流仅用于水平包装。
  • GridLayout 不起作用,因为组件的大小适合可用空间。 BoxLayout 或 GridBagLayout 可用于垂直添加组件。

标签: java swing jscrollpane cardlayout springlayout


【解决方案1】:

我自己也遇到过一些问题。对我有用的是使用边框布局。您需要在添加新元素后调用 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 中删除元素,如果您不这样做,它们将保持可见,直到您绘制它们。

【讨论】:

  • 方法名称不应以大写字符开头。
  • 我自己最近一直在远离它,这是我更改的一些旧代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2013-10-20
  • 2014-05-22
  • 1970-01-01
  • 2020-11-30
相关资源
最近更新 更多