0

I have a JScrollPane whose viewport is a JPanel. The JPanel contains smaller JPanels that take up the entire viewport's width, and the big JPanel is set to a FlowLayout. The user should be able to add as many JPanels as they want (well, up to 200 for my purposes), and they should be able to scroll down the JScrollPane to see everything they have added. Basically I'm just trying to make the JScrollPane grow. I'm calculating what I thought the JPanel's height should be like this:

Dimension dimension = new Dimension(width, smallPanel.height * totalPanels
+ ((FlowLayout) getLayout()).getVGap * totalPanels);

setPreferredSize(dimension);

And it mostly works, but as you add more, it starts cutting the smaller JPanels off, and the bottom panel eventually isn't shown. Is there a way that I can determine the size of the JPanel for the viewport so that I wouldn't have to calculate its dimensions with variables? Like pack() does for JFrame? Or do I need to keep guessing and checking?

Thanks

kneedhelp
  • 555
  • 4
  • 18
  • 1
    To start with, don't use `setPreferredSize(dimension);`, let the panel's layout manager do it's job and calculate the preferred/minimum/maximum size it needs in order to accommodate the child components. `FlowLayout` might not be the best choice here, you could use `GridBagLayout` or `VerticalLayout` from SwingLab's SwingX library, or Rob's [`WrapLayout`](https://tips4java.wordpress.com/2008/11/06/wrap-layout/) – MadProgrammer Nov 09 '15 at 23:13
  • 1
    Don't use FlowLayout, but rather another layout or perhaps nested JPanels, each with its own layout. I can't give more specific recommendations since I don't fully understand what you're trying to achieve. Also, hopefully you meant that the viewport's view is a JPanel and not the viewport itself. – Hovercraft Full Of Eels Nov 09 '15 at 23:13
  • For [example](http://stackoverflow.com/questions/19148603/resizable-layout-swing-when-disappears-jpanel/19149113#19149113) – MadProgrammer Nov 09 '15 at 23:16
  • See [BorderLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html) and [GridLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html) for using multiple child JPanels. – Perry Monschau Nov 09 '15 at 23:17
  • I'll try these layouts. Thanks guys – kneedhelp Nov 09 '15 at 23:25

0 Answers0