4

I have a bunch of buttons on a JPanel using a FlowLayout. It looks really nice. When the buttons reach the right side of the panel they start out on a new row creating a nice 2-dimensional grid.

Here is the code:

    Container cp = getContentPane();
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    for (int i = 0; i < 20; i++)
        panel.add(new JButton("Button " + i));
    cp.add(panel);

However, the minute I put the panel in a scroll pane with only vertical scrolling:

    Container cp = getContentPane();
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    for (int i = 0; i < 20; i++)
        panel.add(new JButton("Button " + i));
    JScrollPane pane = new JScrollPane(
            panel,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    cp.add(pane);

the buttons are only shown in one row (and I can't even see the ones off to the right). I still want them to wrap. What is going on here? By the way, I need to show only the vertical scroll bar and no horizontal scroll bar. I want the buttons to wrap to a new row when they reach the right end.

Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
  • Why don't you read the answers in your last question? – camickr Apr 20 '11 at 19:30
  • I did read the answers in my last question (in fact, I commented on a couple of them). I realized I was asking the wrong question. I do want a FlowLayout. I'm just confused as to why adding the JScrollPane causes the buttons not to wrap onto new lines when they reach the right-hand side. – Paul Reiners Apr 20 '11 at 19:33
  • 1
    If you say so, but I gave you the answer over 2 hours ago. – camickr Apr 20 '11 at 19:44

1 Answers1

4

Check out my answer here: How can I let JToolBars wrap to the next line (FlowLayout) without them being hidden ty the JPanel below them?

There is a custom Flow Layout that I have used in this exact situation. Just plug it in and it wraps even in a scroll pane.

Community
  • 1
  • 1
jzd
  • 23,473
  • 9
  • 54
  • 76