Based on the comment of Hovercraft Full Of Eels, I'll answer my own question.
Calling JLayeredPane.add(Component comp, Object constraints)
will call addImpl(Component comp, Object constraints, int index)
. This method is overridden by JLayeredPane itself, here's the source:
protected void addImpl(Component comp, Object constraints, int index) {
int layer;
int pos;
if(constraints instanceof Integer) {
layer = ((Integer)constraints).intValue();
setLayer(comp, layer);
} else
layer = getLayer(comp);
pos = insertIndexForLayer(layer, index);
super.addImpl(comp, constraints, pos);
comp.validate();
comp.repaint();
validateOptimizedDrawing();
}
As you can see, the Integer
object is intercepted, so that the JLayeredPane knows the layer in which comp
should be placed. Then, it passes on constraints
, the Integer, to the super implementation. The essential part in the super implementation, Container
, is:
protected void addImpl(Component comp, Object constraints, int index) {
...
if (layoutMgr != null) {
if (layoutMgr instanceof LayoutManager2) {
((LayoutManager2)layoutMgr).addLayoutComponent(comp, constraints);
} else if (constraints instanceof String) {
layoutMgr.addLayoutComponent((String)constraints, comp);
}
}
...
}
The solution would therefore be to extend JLayeredPane
and override its addImpl(Component comp, Object constraints, int index)
method, which can accept any Object of your choice: this object should contain the Integer
needed for the JLayeredPane's layer decision, and it should also contain the constraints object for the chosen LayoutManager.
StackConstraints:
public final class StackConstraints {
public final int layer;
public final Object layoutConstraints;
public StackConstraints (int layer, Object layoutConstraints){
this.layer = layer;
this.layoutConstraints = layoutConstraints;
}
}
JLayeredPane extension:
protected void addImpl(Component comp, Object constraints, int index) {
int layer;
int pos;
Object constr;
if(constraints instanceof StackConstraints) {
layer = constraints.layer.intValue();
constr = ((StackConstraints) constraints).layoutConstraints;
setLayer(comp, layer);
} else {
layer = getLayer(comp);
constr = constraints;
}
pos = insertIndexForLayer(layer, index);
super.addImpl(comp, constraints, pos);
comp.validate();
comp.repaint();
validateOptimizedDrawing();
}