As you correctly state, each component has to have exactly one parent. Therefore, you have to add JPanel 1, JPanel 2 and JComponent to a common container.
What I would suggest is adding JPanel 1 and JPanel 2 to another JPanel with, say, a BorderLayout or GridLayout, then add that JPanel and your overlaying JComponent to yet another JPanel and use a custom layout manager.
Look into the interface LayoutManager
- it arranges the bounds and positions of components in a container. It's actually not difficult to implement, assuming you know what you want. In this particular case, the JComponent could be laid out relative to the two JPanel components which could be passed explicitly to the LayoutManager
implementation.
This would be a very specific solution, but you could also generalize it by using LayoutManager2
instead of LayoutManager
. LayoutManager2
allows to use constraint objects for the components to be laid out. Each constraint is a plain Java object which describes the layout of a component. It is specific to the LayoutManager2
implementation used.