Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JScrollpane within the CENTER of a BorderLayout

I have the following code:

    package example;

    import java.awt.BorderLayout;
    import java.awt.FlowLayout;

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;

    public class ScrollingExample extends JFrame
    {
        private static final long serialVersionUID = 1L;

        public static void main(String[] args)
        {
            ScrollingExample scrollingExample = new ScrollingExample();
            scrollingExample.go();
        }

        private void go()
        {
            JPanel topPanel = new JPanel();
            topPanel.add(new JLabel("boo"));

            JPanel mainPanel = new JPanel();
            JPanel mainInnerPanel = makeMainInnerPanel();

            JScrollPane scrollPane = new JScrollPane(mainInnerPanel);
            mainPanel.add(scrollPane);
            add(topPanel, BorderLayout.NORTH);
            add(mainPanel, BorderLayout.CENTER);

            pack();
            setVisible(true);
        }

        private JPanel makeMainInnerPanel()
        {
            JPanel row1 = makeHorizontalPanel("one", "two", "three", "four", "five");
            JPanel row2 = makeHorizontalPanel("six", "seven", "eight");
            JPanel row3 = makeHorizontalPanel("nine", "ten", "eleven");
            JPanel mainInnerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            mainInnerPanel.add(row1);
            mainInnerPanel.add(row2);
            mainInnerPanel.add(row3);
            return mainInnerPanel;
        }

        private JPanel makeHorizontalPanel(String ... labelValues)
        {
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            for (String s : labelValues)
            {
                JLabel label = new JLabel(s);
                panel.add(label);
            }
            return panel;
        }
    }

When I display it, it sizes itself to show all the labels; when I resize the window, I can't get scrollbars to show up.

When I get this working, I want to make a panel that contains a JTabbedPane and a couple of buttons, and I want THAT to have scroll bars if the user sizes the window so that some part of it cannot be seen. If the answer to this question needs something additional or different to do that, mentioning it would be appreciated.

like image 547
arcy Avatar asked Jan 27 '26 12:01

arcy


1 Answers

You need to allow the scrollpane to grow/shrink as the window size changes.

There is no need for the "mainPanel".

Just use:

// add(mainPanel, BorderLayout.CENTER);
add(scrollPane, BorderLayout.CENTER);
like image 156
camickr Avatar answered Jan 29 '26 03:01

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!