Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLayeredPane versus Container layering

Tags:

java

swing

JLayeredPane allows one to stack multiple Components on top of one another using JLayeredPane.add(Component, Integer). Components in higher "layers" display on top of Components in lower "layers".

Container.add(Component, int) provides a similar mechanism whereby Components with lower indexes display on top of Components with higher indexes.

Please note that the first mechanism uses Integer and the second mechanism uses int. Also, one renders high values on top of low ones, and the other does the opposite. Do not mix the two :)

My question is: what's the point of using JLayeredPane when Container already provides the same mechanism? Does one layer components better than the another?

UPDATE: There is also Container.setComponentZOrder(Component, int) to consider.

like image 572
Gili Avatar asked Jan 13 '11 15:01

Gili


1 Answers

Answering my own question:

Container.add(Component, int) and Container.setComponentZOrder(Component, int) are virtually identical. The former invokes removeNotify() while the latter does not (for performance reasons).

Container-layering only works if JComponent.isOptimizedDrawingEnabled() returns false. One implementation that just-so-happens to return false is... you guessed it: JLayeredPane

Using Container-layering is discouraged because it can have unexpected side-effects.

Finally, it is worth noting that while Container declares add(Component, int) it doesn't actually paint layered components properly. JComponent and its subclasses do.

Another interesting find: never invoke repaint() on a child of JLayeredPane. This will cause the component to paint itself on top regardless of its z-order. You should only invoke repaint() on the JLayeredPane itself.

like image 58
Gili Avatar answered Oct 11 '22 22:10

Gili