根据 Hovercraft Full Of Eels 的评论,我将回答我自己的问题。
打电话JLayeredPane.add(Component comp, Object constraints)
会打电话addImpl(Component comp, Object constraints, int index)
。这个方法被 JLayeredPane 本身覆盖,这里是源代码:
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();
}
如您所见,Integer
对象被截获,因此 JLayeredPane 知道comp
应该放置的层。然后,它将constraints
Integer 传递给超级实现。超级实现中的基本部分Container
是:
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);
}
}
...
}
因此,解决方案是扩展JLayeredPane
和覆盖其addImpl(Component comp, Object constraints, int index)
方法,该方法可以接受您选择的任何对象:该对象应包含Integer
JLayeredPane 层决策所需的内容,并且还应包含所选 LayoutManager 的约束对象。
堆栈约束:
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 扩展:
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();
}