简体   繁体   English

防止JScrollPane扩展其viewPort组件

[英]Preventing JScrollPane to extend its viewPort component

I have a subPanel to which I occasionally add some components. 我有一个子面板,有时会向其中添加一些组件。 I expect FlowLayout to layout them correctly. 我希望FlowLayout能够正确布局它们。 I put the subPanel in a JScrollPane to let the user see all the components but I wouldn't like to bother the user scrolling horizontally. 我将subPanel放在JScrollPane中,以使用户可以看到所有组件,但我不想打扰用户水平滚动。 But the JScrollPane lets subPanel extend itself horizontally when more componets are added. 但是,当添加更多组件时,JScrollPane允许subPanel水平扩展自身。 In this way all the components are shown in a line horizontally. 这样,所有组件都在水平线上显示。 And this means the worst possible layout. 这意味着最坏的布局。

    this.setLayout(new GridLayout(1, 1));
    subPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
    subPanel.setMaximumSize(new Dimension(500, 4000));
    subPanel.setBackground(Color.CYAN);
    subPane = new JScrollPane(subPanel);
    subPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    subPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    this.add(subPane);

Somewhere else I have added a componentListener to solve the problem but the problem persists: 我在其他地方添加了componentListener来解决问题,但问题仍然存在:

        @Override
        public void componentShown(ComponentEvent e) {
            subPanel.setSize(getSize());
        }

        @Override
        public void componentResized(ComponentEvent e) {
            subPanel.setSize(getSize());
        }

And this is a JPanel that is posed entirely in a JTabbedPane so it occupies all the tab. this是一个完全放在JTabbedPane中的JPanel,因此它占据了所有选项卡。

也许您正在寻找Wrap Layout ,它将在填充水平空间时将组件包装到下一行。

In this way all the components are shown in a line horizontally. 这样,所有组件都在水平线上显示。 And this means the worst possible layout. 这意味着最坏的布局。

But that's exactly what FlowLayout is supposed to do and is exactly what it does. 但这正是FlowLayout应该做的,也正是它要做的。

Why not simply use a BoxLayout oriented to BoxLayout.PAGE_AXIS 为什么不简单地使用面向BoxLayout.PAGE_AXIS的BoxLayout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM