BorderLayout:嵌套的中心面板增长但不调整外面板的大小 [英] BorderLayout: Nested CENTER Panel Grows But does Not Resize Outer Panel

查看:39
本文介绍了BorderLayout:嵌套的中心面板增长但不调整外面板的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主要的 JPanel,它实现了 Scrollable 并使用了 BorderLayout.它包含一个 NORTH 只读 JEditorPane、一个带有 FlowLayout 的 CENTER JPanel,其中 JButton 是动态添加的,以及一个 SOUTH JLabel,所有这些都按该顺序添加.当CENTER JPanel中添加了很多JButton时,按钮会绕到下一行:问题是CENTER JPanel占用的超过一行的垂直空间只是与SOUTH JLabel重叠,并不会导致整个JPanel动态增长或显示垂直滚动条.另一方面,当向 NORTH JEditorPane 添加足够多的文本以使其自动换行到下一行时,它会按照我的预期执行操作并将 CENTER JPanel 向下推并显示垂直滚动条.

I have a main JPanel which implements Scrollable and uses a BorderLayout. It contains one NORTH readonly JEditorPane, one CENTER JPanel with a FlowLayout whereby JButtons are added dynamically, and one SOUTH JLabel, all added in that order. When many JButtons are added to the CENTER JPanel, the buttons wrap onto the next rows: the problem is that the vertical space exceeding one row taken up by the CENTER JPanel just overlaps with the SOUTH JLabel and does not cause the entire JPanel to grow dynamically or show the vertical scrollbar. On the other hand, when enough text is added to NORTH JEditorPane so that it wraps to the next rows, it does behavior as I'd expect and push the CENTER JPanel down and show the vertical scrollbars.

这里主要的 JPanel Scrollable 实现:

Here main JPanel Scrollable implementation:

public Dimension getPreferredScrollableViewportSize() {
    return getPreferredSize();
}

public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
    return Math.max(visibleRect.height * 9 / 10, 1);
}

public boolean getScrollableTracksViewportHeight() {
    if (getParent() instanceof JViewport) {
        JViewport viewport = (JViewport) getParent();
        return getPreferredSize().height < viewport.getHeight();
    }
    return false;
}

public boolean getScrollableTracksViewportWidth() {
    return true;
}

public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
    return Math.max(visibleRect.height / 10, 1);
}

我做错了什么?如何让 CENTER JPanel 向下推 SOUTH JLabel 以增大整个主 JPanel?

What am I doing wrong? How can I make the CENTER JPanel push the SOUTH JLabel down to grow the entire main JPanel?

推荐答案

问题是当按钮被换到下一行时 FlowLayout 不会重新计算首选大小.

The problem is that the FlowLayout does not recalculate the preferred size when buttons are wrapped to the next row.

您应该能够使用 WrapLayout.

WrapLayout 扩展 FlowLayout 并在组件换行到新行时设置适当的首选大小.

WrapLayout extends FlowLayout and sets the proper preferred size when components wrap to a new row.

这篇关于BorderLayout:嵌套的中心面板增长但不调整外面板的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆