javax.swing
Class JLayer<V extends Component>

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JLayer<V>
Type Parameters:
V - the type of JLayer's view component
All Implemented Interfaces:
ImageObserver, MenuContainer, PropertyChangeListener, Serializable, EventListener, Scrollable

public final class JLayer<V extends Component>
extends JComponent
implements Scrollable, PropertyChangeListener

Disabled: no SafeJ information.

JLayer is a universal decorator for Swing components which enables you to implement various advanced painting effects as well as receive notifications of all AWTEvents generated within its borders.

JLayer delegates the handling of painting and input events to a LayerUI object, which performs the actual decoration.

The custom painting implemented in the LayerUI and events notification work for the JLayer itself and all its subcomponents. This combination enables you to enrich existing components by adding new advanced functionality such as temporary locking of a hierarchy, data tips for compound components, enhanced mouse scrolling etc and so on.

JLayer is a good solution if you only need to do custom painting over compound component or catch input events from its subcomponents.

 import javax.swing.*;
 import javax.swing.plaf.LayerUI;
 import java.awt.*;

 public class JLayerSample {

     private static JLayer<JComponent> createLayer() {
         // This custom layerUI will fill the layer with translucent green
         // and print out all mouseMotion events generated within its borders
         LayerUI<JComponent> layerUI = new LayerUI<JComponent>() {

             public void paint(Graphics g, JComponent c) {
                 // paint the layer as is
                 super.paint(g, c);
                 // fill it with the translucent green
                 g.setColor(new Color(0, 128, 0, 128));
                 g.fillRect(0, 0, c.getWidth(), c.getHeight());
             }

             public void installUI(JComponent c) {
                 super.installUI(c);
                 // enable mouse motion events for the layer's subcomponents
                 ((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK);
             }

             public void uninstallUI(JComponent c) {
                 super.uninstallUI(c);
                 // reset the layer event mask
                 ((JLayer) c).setLayerEventMask(0);
             }

             // overridden method which catches MouseMotion events
             public void eventDispatched(AWTEvent e, JLayer<? extends JComponent> l) {
                 System.out.println("AWTEvent detected: " + e);
             }
         };
         // create a component to be decorated with the layer
         JPanel panel = new JPanel();
         panel.add(new JButton("JButton"));

         // create the layer for the panel using our custom layerUI
         return new JLayer<JComponent>(panel, layerUI);
     }

     private static void createAndShowGUI() {
         final JFrame frame = new JFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         // work with the layer as with any other Swing component
         frame.add(createLayer());

         frame.setSize(200, 200);
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);
     }

     public static void main(String[] args) throws Exception {
         SwingUtilities.invokeAndWait(new Runnable() {
             public void run() {
                 createAndShowGUI();
             }
         });
     }
 }
 
Note: JLayer doesn't support the following methods: using any of of them will cause UnsupportedOperationException to be thrown, to add a component to JLayer use setView(Component) or setGlassPane(JPanel).

Since:
1.7
See Also:
JLayer(Component), setView(Component), getView(), LayerUI, JLayer(Component, LayerUI), setUI(javax.swing.plaf.LayerUI), getUI()

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JLayer()
          Creates a new JLayer object with a null view component and null LayerUI.
JLayer(V view)
          Creates a new JLayer object with null LayerUI.
JLayer(V view, LayerUI<V> ui)
          Creates a new JLayer object with the specified view component and LayerUI object.
 
Method Summary
protected  void addImpl(Component comp, Object constraints, int index)
          This method is not supported by JLayer and always throws UnsupportedOperationException
 void addNotify()
          Notifies this component that it now has a parent component.
 JPanel createGlassPane()
          Called by the constructor methods to create a default glassPane.
 JPanel getGlassPane()
          Returns the JLayer's glassPane component or null.
 long getLayerEventMask()
          Returns the bitmap of event mask to receive by this JLayer and its LayerUI.
 Dimension getPreferredScrollableViewportSize()
          Returns the preferred size of the viewport for a view component.
 int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
          Returns a scroll increment, which is required for components that display logical rows or columns in order to completely expose one block of rows or columns, depending on the value of orientation.
 boolean getScrollableTracksViewportHeight()
          Returns false to indicate that the height of the viewport does not determine the height of the layer, unless the preferred height of the layer is smaller than the height of the viewport.
 boolean getScrollableTracksViewportWidth()
          Returns false to indicate that the width of the viewport does not determine the width of the layer, unless the preferred width of the layer is smaller than the width of the viewport.
 int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
          Returns a scroll increment, which is required for components that display logical rows or columns in order to completely expose one new row or column, depending on the value of orientation.
 LayerUI<? super V> getUI()
          Returns the LayerUI for this JLayer.
 V getView()
          Returns the JLayer's view component or null.
 boolean isOptimizedDrawingEnabled()
          To enable the correct painting of the glassPane and view component, the JLayer overrides the default implementation of this method to return false when the glassPane is visible.
 void paint(Graphics g)
          Delegates all painting to the LayerUI object.
protected  void paintComponent(Graphics g)
          This method is empty, because all painting is done by paint(Graphics) and ComponentUI.update(Graphics, JComponent) methods
 void propertyChange(PropertyChangeEvent evt)
          This method gets called when a bound property is changed.
 void remove(Component comp)
          Removes the specified component from this container.
 void removeAll()
          Removes all the components from this container.
 void removeNotify()
          Notifies this component that it no longer has a parent component.
 void setGlassPane(JPanel glassPane)
          Sets the JLayer's glassPane component, which can be null.
 void setLayerEventMask(long layerEventMask)
          Sets the bitmask of event types to receive by this JLayer.
 void setUI(LayerUI<? super V> ui)
          Sets the LayerUI which will perform painting and receive input events for this JLayer.
 void setView(V view)
          Sets the JLayer's view component, which can be null.
 void updateUI()
          Delegates its functionality to the LayerUI.updateUI(JLayer) method, if LayerUI is set.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JLayer

public JLayer()
Class is disabled.

Creates a new JLayer object with a null view component and null LayerUI.

See Also:
setView(V), setUI(javax.swing.plaf.LayerUI)

JLayer

public JLayer(V view)
Class is disabled.

Creates a new JLayer object with null LayerUI.

Parameters:
view - the component to be decorated by this JLayer
See Also:
setUI(javax.swing.plaf.LayerUI)

JLayer

public JLayer(V view,
              LayerUI<V> ui)
Class is disabled.

Creates a new JLayer object with the specified view component and LayerUI object.

Parameters:
view - the component to be decorated
ui - the LayerUI delegate to be used by this JLayer
Method Detail

getView

public V getView()
Class is disabled.

Returns the JLayer's view component or null.
This is a bound property.

Returns:
the JLayer's view component or null if none exists
See Also:
setView(Component)

setView

public void setView(V view)
Class is disabled.

Sets the JLayer's view component, which can be null.
This is a bound property.

Parameters:
view - the view component for this JLayer
See Also:
getView()

setUI

public void setUI(LayerUI<? super V> ui)
Class is disabled.

Sets the LayerUI which will perform painting and receive input events for this JLayer.

Parameters:
ui - the LayerUI for this JLayer

getUI

public LayerUI<? super V> getUI()
Class is disabled.

Returns the LayerUI for this JLayer.

Returns:
the LayerUI for this JLayer

getGlassPane

public JPanel getGlassPane()
Class is disabled.

Returns the JLayer's glassPane component or null.
This is a bound property.

Returns:
the JLayer's glassPane component or null if none exists
See Also:
setGlassPane(JPanel)

setGlassPane

public void setGlassPane(JPanel glassPane)
Class is disabled.

Sets the JLayer's glassPane component, which can be null.
This is a bound property.

Parameters:
glassPane - the glassPane component of this JLayer
See Also:
getGlassPane()

createGlassPane

public JPanel createGlassPane()
Class is disabled.

Called by the constructor methods to create a default glassPane. By default this method creates a new JPanel with visibility set to true and opacity set to false.

Returns:
the default glassPane

addImpl

protected void addImpl(Component comp,
                       Object constraints,
                       int index)
Class is disabled.

This method is not supported by JLayer and always throws UnsupportedOperationException

Overrides:
addImpl in class Container
Parameters:
comp - the component to be added
constraints - an object expressing layout constraints for this component
index - the position in the container's list at which to insert the component, where -1 means append to the end
Throws:
UnsupportedOperationException - this method is not supported
See Also:
setView(Component), setGlassPane(JPanel)

remove

public void remove(Component comp)
Class is disabled.

Removes the specified component from this container. This method also notifies the layout manager to remove the component from this container's layout via the removeLayoutComponent method.

This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.

Overrides:
remove in class Container
Parameters:
comp - the component to be removed
See Also:
Container.add(java.awt.Component), Container.invalidate(), Container.validate(), Container.remove(int)

removeAll

public void removeAll()
Class is disabled.

Removes all the components from this container. This method also notifies the layout manager to remove the components from this container's layout via the removeLayoutComponent method.

This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.

Overrides:
removeAll in class Container
See Also:
Container.add(java.awt.Component), Container.remove(int), Container.invalidate()

paint

public void paint(Graphics g)
Class is disabled.

Delegates all painting to the LayerUI object.

Overrides:
paint in class JComponent
Parameters:
g - the Graphics to render to
See Also:
JComponent.paintComponent(java.awt.Graphics), JComponent.paintBorder(java.awt.Graphics), JComponent.paintChildren(java.awt.Graphics), JComponent.getComponentGraphics(java.awt.Graphics), JComponent.repaint(long, int, int, int, int)

paintComponent

protected void paintComponent(Graphics g)
Class is disabled.

This method is empty, because all painting is done by paint(Graphics) and ComponentUI.update(Graphics, JComponent) methods

Overrides:
paintComponent in class JComponent
Parameters:
g - the Graphics object to protect
See Also:
JComponent.paint(java.awt.Graphics), ComponentUI

isOptimizedDrawingEnabled

public boolean isOptimizedDrawingEnabled()
Class is disabled.

To enable the correct painting of the glassPane and view component, the JLayer overrides the default implementation of this method to return false when the glassPane is visible.

Overrides:
isOptimizedDrawingEnabled in class JComponent
Returns:
false if JLayer's glassPane is visible

propertyChange

public void propertyChange(PropertyChangeEvent evt)
Class is disabled.

This method gets called when a bound property is changed.

Specified by:
propertyChange in interface PropertyChangeListener
Parameters:
evt - A PropertyChangeEvent object describing the event source and the property that has changed.

setLayerEventMask

public void setLayerEventMask(long layerEventMask)
Class is disabled.

Sets the bitmask of event types to receive by this JLayer. Here is the list of the supported event types:

If LayerUI is installed, LayerUI.eventDispatched(AWTEvent, JLayer) method will only receive events that match the event mask.

The following example shows how to correclty use this method in the LayerUI implementations:

    public void installUI(JComponent c) {
       super.installUI(c);
       JLayer l = (JLayer) c;
       // this LayerUI will receive only key and focus events
       l.setLayerEventMask(AWTEvent.KEY_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
    }

    public void uninstallUI(JComponent c) {
       super.uninstallUI(c);
       JLayer l = (JLayer) c;
       // JLayer must be returned to its initial state
       l.setLayerEventMask(0);
    }
 
By default JLayer receives no events.

Parameters:
layerEventMask - the bitmask of event types to receive
Throws:
IllegalArgumentException - if the layerEventMask parameter contains unsupported event types
See Also:
getLayerEventMask()

getLayerEventMask

public long getLayerEventMask()
Class is disabled.

Returns the bitmap of event mask to receive by this JLayer and its LayerUI.

It means that LayerUI.eventDispatched(AWTEvent, JLayer) method will only receive events that match the event mask.

By default JLayer receives no events.

Returns:
the bitmask of event types to receive for this JLayer

updateUI

public void updateUI()
Class is disabled.

Delegates its functionality to the LayerUI.updateUI(JLayer) method, if LayerUI is set.

Overrides:
updateUI in class JComponent
See Also:
JComponent.setUI(javax.swing.plaf.ComponentUI), UIManager.getLookAndFeel(), UIManager.getUI(javax.swing.JComponent)

getPreferredScrollableViewportSize

public Dimension getPreferredScrollableViewportSize()
Class is disabled.

Returns the preferred size of the viewport for a view component.

If the ui delegate of this layer is not null, this method delegates its implementation to the LayerUI.getPreferredScrollableViewportSize(JLayer)

Specified by:
getPreferredScrollableViewportSize in interface Scrollable
Returns:
the preferred size of the viewport for a view component
See Also:
Scrollable, LayerUI.getPreferredScrollableViewportSize(JLayer)

getScrollableBlockIncrement

public int getScrollableBlockIncrement(Rectangle visibleRect,
                                       int orientation,
                                       int direction)
Class is disabled.

Returns a scroll increment, which is required for components that display logical rows or columns in order to completely expose one block of rows or columns, depending on the value of orientation.

If the ui delegate of this layer is not null, this method delegates its implementation to the LayerUI.getScrollableBlockIncrement(JLayer,Rectangle,int,int)

Specified by:
getScrollableBlockIncrement in interface Scrollable
Parameters:
visibleRect - The view area visible within the viewport
orientation - Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
direction - Less than zero to scroll up/left, greater than zero for down/right.
Returns:
the "block" increment for scrolling in the specified direction
See Also:
Scrollable, LayerUI.getScrollableBlockIncrement(JLayer, Rectangle, int, int)

getScrollableTracksViewportHeight

public boolean getScrollableTracksViewportHeight()
Class is disabled.

Returns false to indicate that the height of the viewport does not determine the height of the layer, unless the preferred height of the layer is smaller than the height of the viewport.

If the ui delegate of this layer is not null, this method delegates its implementation to the LayerUI.getScrollableTracksViewportHeight(JLayer)

Specified by:
getScrollableTracksViewportHeight in interface Scrollable
Returns:
whether the layer should track the height of the viewport
See Also:
Scrollable, LayerUI.getScrollableTracksViewportHeight(JLayer)

getScrollableTracksViewportWidth

public boolean getScrollableTracksViewportWidth()
Class is disabled.

Returns false to indicate that the width of the viewport does not determine the width of the layer, unless the preferred width of the layer is smaller than the width of the viewport.

If the ui delegate of this layer is not null, this method delegates its implementation to the LayerUI.getScrollableTracksViewportWidth(JLayer)

Specified by:
getScrollableTracksViewportWidth in interface Scrollable
Returns:
whether the layer should track the width of the viewport
See Also:
Scrollable, LayerUI.getScrollableTracksViewportWidth(JLayer)

getScrollableUnitIncrement

public int getScrollableUnitIncrement(Rectangle visibleRect,
                                      int orientation,
                                      int direction)
Class is disabled.

Returns a scroll increment, which is required for components that display logical rows or columns in order to completely expose one new row or column, depending on the value of orientation. Ideally, components should handle a partially exposed row or column by returning the distance required to completely expose the item.

Scrolling containers, like JScrollPane, will use this method each time the user requests a unit scroll.

If the ui delegate of this layer is not null, this method delegates its implementation to the LayerUI.getScrollableUnitIncrement(JLayer,Rectangle,int,int)

Specified by:
getScrollableUnitIncrement in interface Scrollable
Parameters:
visibleRect - The view area visible within the viewport
orientation - Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
direction - Less than zero to scroll up/left, greater than zero for down/right.
Returns:
The "unit" increment for scrolling in the specified direction. This value should always be positive.
See Also:
Scrollable, LayerUI.getScrollableUnitIncrement(JLayer, Rectangle, int, int)

addNotify

public void addNotify()
Class is disabled.

Notifies this component that it now has a parent component. When this method is invoked, the chain of parent components is set up with KeyboardAction event listeners.

Overrides:
addNotify in class JComponent
See Also:
JComponent.registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int)

removeNotify

public void removeNotify()
Class is disabled.

Notifies this component that it no longer has a parent component. When this method is invoked, any KeyboardActions set up in the the chain of parent components are removed.

Overrides:
removeNotify in class JComponent
See Also:
JComponent.registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int)