I have a JFrame
containing a set of JPanels
in a CardLayout
. Each JPanel
has a different size and I want the JFrame
to adapt to the size of the currently displayed JPanel
(not the JPanel
to adapt to the size of the JFrame
).
How can I achieve this?
The general is: if you have a layout problem, always solve it with an appropriate LayoutManager. Never tweak a component's sizing hint to reach your goal.
In this case, it's particularly easy to adjust the CardLayout. By default, it calculates its prefSize to the max of prefSizes of all cards. Simply subclass and implement to return the prefSize (plus insets) of the currently visible card:
Using that (borrowing @mKorbel's example), the main method cleanly shrinks down:
Here is the SSCCE.
1) For continuous increase/decrease of size, you should look for some animation API.
or
2) If isn't there any background task with output to the GUI, you can to pause while sizing the
JFrame
. In that case, you would delay the increase/decrease by usingThread#sleep(int)
wrapped intoRunnable
thread.3) Notice (not for OP) using
Thread#sleep(int)
directly during EDT would be freeze GUI until the delay ended.I think you may have the wrong layout manager for what you want to do (leaving aside, for the moment, that I am not sure you want to do what you say you want to do).
I have not yet found documentation on what I suspect, which is that CardLayout resizes all of its children to the size of its container. I did find the following comment for its "layoutContainer" method:
I think this is reasonable behavior, since it would be very annoying for a user to have the panel size jump around as panels are traversed.
If this is really the behavior you want, then I think you want a different layout manager. And since it is unusual behavior for a UI in general, you may well not find a standard one to do this particular 'feature', so you may have to write your own.