Preventing JScrollPane to extend its viewPort component

164 views Asked by At

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.

2

There are 2 answers

3
camickr On BEST ANSWER

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

3
Hovercraft Full Of Eels On

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