2

I have a JPanel inside of a JScrollPane which is nested inside some other containers. My JPanel uses a modified FlowLayout from SO user jxd in this question.

This may be information overkill but the full nesting of the panel in question is as follows:

JPanel (ModifiedFlowLayout) > JScrollPane > JPanel (GridBagLayout) > JTabbedPane > JPanel (GridBagLayout) > JSplitPane > JPanel (BorderLayout) > JFrame.

The problem is that when I call pack() on my JFrame the JScrollPane/JPanel expands horizontally to fill the entire remaining screen space (across multiple monitors). The space used is more than is needed to display all of the components in the JPanel. I tried using setMaximumSize() on my JPanel but it seems to be ignored in this scenario.

Ideally I would like the panel to have it's size dictated by space left after sizing the components that surround it. Can/how can this been done?

Community
  • 1
  • 1
Fr33dan
  • 4,227
  • 3
  • 35
  • 62
  • Did you try overriding `getPreferredSize()`? – nachokk Mar 12 '14 at 15:54
  • @nachokk Well I'll be damned. I thought maximum size would be a more important factor than preferred size but setting that seems to have prevented the expanding although it has caused the ModifiedFlowLayout to start behaving improperly but that may be a different issue. Also I didn't override it since I have only used JPanel not extended it. I used `setPreferedSize()` instead. – Fr33dan Mar 12 '14 at 16:02
  • [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – nachokk Mar 12 '14 at 16:05
  • @nachokk Interesting find that now the panel is still gigantic (this wasn't easily seen given I used `HORIZONTAL_SCROLLBAR_NEVER`) and mostly empty but it does not expand the entire frame when packed. – Fr33dan Mar 12 '14 at 16:06

1 Answers1

0

The preferred size of a FlowLayout will try to display all components on a single row. I don't know how the ModifiedFlowLayout works but you can check out Wrap Layout which does the same thing.

However, when using Wrap Layout you can use the setSize(...) method to make a suggestion as to what the initial width should be. Initial wrapping of components should then be based on that size.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I tried it and it seems WrapLayout and ModifiedFlowLayout have the same behavior. @nachokk's comment to use preferred size instead of maximum size turned out to be the solution to the question at hand but he did not post it as an answer thus I cannot mark it. – Fr33dan Mar 12 '14 at 17:31
  • @Fr33dan, you should NOT be using setPreferredSize(). The layout will not dynamically change if the user ever resizes the frame. – camickr Mar 12 '14 at 17:49
  • That is true if I use `setPreferredSize()` on my JPanel if I do it directly to my JScrollPane it works as desired. – Fr33dan Mar 12 '14 at 18:10