I got the same problem as you and for me I m satisfied with my solution I share it may be it help you on your context
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Housseyn
*/
public class JPanelTools {
public static final void ShowPanel(JPanel target, JPanel object) {
target.removeAll();
Dimension size = object.getSize();
size.setSize(size.width, target.getHeight());
target.setSize(object.getSize());
GridBagLayout gridBagLayout = new GridBagLayout();
target.setLayout(gridBagLayout);
GridBagConstraints gbc = new GridBagConstraints(target.getX(),
target.getY(),
target.getWidth(),
target.getHeight(),
0, 0,
GridBagConstraints.ABOVE_BASELINE,
0,
new Insets(5, 5, 5, 5),
0, 0);
target.add(object, gbc);
target.invalidate();
target.revalidate();
target.validate();
target.repaint();
target.show();
object.validate();
object.repaint();
object.show();
Container Frame = target.getParent();
Container Current = target.getParent();
while ((Current != null)) {
System.out.println("current =" + Current.getClass().getName());
Frame = Current;
Current = Current.getParent();
}
System.out.println("frame " + Frame.getClass().getName());
if (Frame != null) {
System.out.println("pack");
JFrame MyFrame = (JFrame) Frame;
int extendedState = MyFrame.getExtendedState();
if (extendedState != JFrame.MAXIMIZED_BOTH) {
MyFrame.pack();
MyFrame.setExtendedState(extendedState);
}
}
}
}
I designed an empty panel on my main Frame and in a button I call this
MyDesignedPanel myPanel = new MyDesignedPanel();
JPanelTools.ShowPanel(JemptyPanel, myPanel);
that works perfectly for me