views:

231

answers:

1

I'm trying to figure something out about JLayeredPane in Swing. If anyone has used this class, feedback would be appreciated.

The documentation for getLayer(JComponent c) states:

Gets the layer property for a JComponent, it does not cause any side effects like setLayer(). (painting, add/remove, etc) Normally you should use the instance method getLayer().

Clearly, there is some mistake here since this is the instance method getLayer() (there aren't overloaded versions)

Is there actually a different call that should be made here, or was somebody just too eager in copying from putLayer():

Sets the layer property on a JComponent. This method does not cause any side effects like setLayer() (painting, add/remove, etc). Normally you should use the instance method setLayer(), in order to get the desired side-effects (like repainting).

+1  A: 

Like many things in Swing, the answer to your question is revealed in the swing source code. From JLayeredPane.java:

public static int getLayer(JComponent c) {
    Integer i;
    if((i = (Integer)c.getClientProperty(LAYER_PROPERTY)) != null)
        return i.intValue();
    return DEFAULT_LAYER.intValue();
}

public int getLayer(Component c) {
    Integer i;
    if(c instanceof JComponent)
        i = (Integer)((JComponent)c).getClientProperty(LAYER_PROPERTY);
    else
        i = (Integer)getComponentToLayer().get((Component)c);

    if(i == null)
        return DEFAULT_LAYER.intValue();
    return i.intValue();
}

It looks like the reason you are seeing some differences here is that the layer of a JComponent instance is stored as a property of the JComponent instance, but the layer of a Component instance is stored within a hashtable of JLayeredPane. Hence, getLayer(JComponent c) can be static while getLayer(Component c) cannot.

As you might imagine, this is just the start of the strangeness of this class. Validating and painting JLayeredPane and contents can get complicated quickly.

Gary