I have 3 JPanels (let's name each one as "BLOCK") in another JPanel (let's name it "CENTER_DECORS") inside JScollPane that sits in one of tabs of JTabbedPane.
Now: when I dynamically change the height of any of those BLOCK-s ("fold" them by setting their height from 150 to 20) I want the other BLOCK-s to update their vertical position accordingly so that they would still stack on each other, but as of now I have "hole" between the BLOCK with changed (lowered) height and the next one.
I am using BoxLayout for the CENTER_DECORS JPanel:
CENTER_DECORS.setLayout(new BoxLayout(CENTER_DECORS, BoxLayout.Y_AXIS));
After I change the height of a BLOCK...
BLOCK.setSize(BLOCK.getWidth(), 20);
...I call immediately this code:
CENTER_DECORS.repaint();
CENTER_DECORS.validate();
CENTER_DECORS.revalidate();
Strangely enough nothing happens at all, not even the height is changed, but when I leave just:
CENTER_DECORS.repaint();
...then it at least change the height but no stacking-on-each-other occurs.
UPDATE: the solution must have option to storing folded/unfolded state with each row so when program starts it could gp to the appropriate state (folded/expanded).
Does anyone know of a solution so that those BLOCK-s would still stick to each other vertically when their height is changed?
EDIT: only after I fully tested @MadProgrammer solution I realized the duplicate answer is not the correct one as it only allows 1 "block" to be expanded/opened at a time and I need it to be expanded freely no matter how many "blocks" + his code starts with everything folded/collapsed and I need it to be in their normal that is - most of the time - expanded state + my solution doesn't require any special listener to be used (except MouseListener for button states which is normal, of course), thus less coding.
So, after fiddling around whole day I finally made my own version inspired by @MadProgrammer's approach - my code now behaves exactly s I wanted (reason I was searching for this solution was that my application may have like tens of different "block" in a JPanel that are quite hard to manage as they occupy too many space which may be most of the time not needed so option to fold those up would be very good option to have), so this code below is actually the right solution, please, remove that "duplicate" thing as it is no longer accurate (see my separate answer below).