Exploring JDK 7, Part 3: Decorating Swing Components with JLayer
Oracle’s release of JDK 7 is expected to occur this coming fall. This new release will offer a suite of new features for you to learn.
JDK 7 introduces a new Swing component that serves as a universal decorator for Swing components. This new component is implemented as the javax.swing.JLayer class, and is based upon JXLayer, a part of the Swing Helper project from Swing Labs.
JLayer works with the new javax.swing.plaf.LayerUI class to let you implement advanced painting effects and receive notifications of all java.awt.AWTEvents generated within its borders. This article introduces you to these classes.
An Overview of JLayer and LayerUI
According to its JDK documentation, JLayer delegates the handling of painting and input events to a LayerUI object, which performs the decoration. You can use these classes to enrich existing components by modifying their appearances and ehaviors.
Essentially, you extend LayerUI and override various methods to enable custom painting and event handling, and then pass an instance of this class, along with the component to be decorated, to the following JLayer constructor:
public JLayer(V view, LayerUI<V> ui)
The first argument, any class extending java.awt.Component, identifies the Swing component you want to decorate. This component can be a JPanel or another container; the container and all contained components will be decorated. The second argument identifies the decorator.
Along with the aforementioned constructor, JLayer provides a no-argument constructor, and a constructor that takes only a view (the component being decorated) argument. Use these constructors to delay specifying a LayerUI instance and/or a view when creating a JLayer.
If you don't initially specify a view, you can later provide the view by invoking JLayer's public void setView(V view) method. This class also provides a public V getView() method to return the component being decorated or null.
If you don't initially specify a LayerUI instance, you can later provide this instance by invoking JLayer's public void setUI(LayerUI<? super V> ui method. This class also provides a public LayerUI<? super V> getUI() method to return the current decorator or null.