开发者

JLayeredPane versus Container layering

开发者 https://www.devze.com 2023-02-04 18:47 出处:网络
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\".

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 mechan开发者_JAVA百科ism 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.


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.


My take on this is that the Container.add(Component,int) and the JLayeredPane.add(Component,Integer) functions set the component being added at a certain index. It is then this index that is used by layout managers to handle position, layout, and order of painting of the component. I think JLayeredPane.setLayer(Component c, int layer) is more what your looking for as far as layers go. It is specifically created to layer the components. Just my two sense.

0

精彩评论

暂无评论...
验证码 换一张
取 消