I have a subPanel to which I occasionally add some components. I expect FlowLayout to layout them correctly. 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. But the JScrollPane lets subPanel extend itself horizontally when more componets are added. 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:

        @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.

有帮助吗?

解决方案

Maybe you are looking for the Wrap Layout, which will wrap components to the next line when the horizontal space is filled.

其他提示

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.

Why not simply use a BoxLayout oriented to BoxLayout.PAGE_AXIS

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top