- Type Parameters:
- V- the type of- JLayer's view component
- All Implemented Interfaces:
- ImageObserver,- MenuContainer,- PropertyChangeListener,- Serializable,- EventListener,- Accessible,- Scrollable
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(WindowConstants.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:
 - Container.add(java.awt.Component)
- Container.add(String, java.awt.Component)
- Container.add(java.awt.Component, int)
- Container.add(java.awt.Component, Object)
- Container.add(java.awt.Component, Object, int)
UnsupportedOperationException to be thrown,
 to add a component to JLayer
 use setView(Component) or setGlassPane(JPanel).- 
Nested Class SummaryNested classes/interfaces declared in class javax.swing.JComponentJComponent.AccessibleJComponentNested classes/interfaces declared in class java.awt.ContainerContainer.AccessibleAWTContainerNested classes/interfaces declared in class java.awt.ComponentComponent.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
- 
Field SummaryFields declared in class javax.swing.JComponentlistenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields declared in class java.awt.ComponentaccessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields declared in interface java.awt.image.ImageObserverABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionprotected voidThis method is not supported byJLayerand always throwsUnsupportedOperationExceptionCalled by the constructor methods to create a defaultglassPane.voiddoLayout()Delegates its functionality to theLayerUI.doLayout(JLayer)method, ifLayerUIis set.Gets the AccessibleContext associated with thisJLayer.Delegates its functionality to thegetView().getBorder()method, if the view component is an instance ofjavax.swing.JComponent, otherwise returnsnull.Returns theJLayer's glassPane component ornull.longReturns the bitmap of event mask to receive by thisJLayerand itsLayerUI.Returns the preferred size of the viewport for a view component.intgetScrollableBlockIncrement(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.booleanReturnsfalseto 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.booleanReturnsfalseto 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.intgetScrollableUnitIncrement(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.getUI()Returns theLayerUIfor thisJLayer.getView()Returns theJLayer's view component ornull.booleanimageUpdate(Image img, int infoflags, int x, int y, int w, int h) Delegates its functionality to theLayerUI.imageUpdate(java.awt.Image, int, int, int, int, int, JLayer)method, if theLayerUIis set.booleanTheJLayeroverrides the default implementation of this method (inJComponent) to returnfalse.protected booleanAlways returnstrueto cause painting to originate fromJLayer, or one of its ancestors.voidDelegates all painting to theLayerUIobject.protected voidThis method is empty, because all painting is done bypaint(Graphics)andComponentUI.update(Graphics, JComponent)methodsvoidpaintImmediately(int x, int y, int w, int h) Delegates its functionality to theLayerUI.paintImmediately(int, int, int, int, JLayer)method, ifLayerUIis set.voidThis method gets called when a bound property is changed.voidDelegates its functionality to thegetView().setBorder(Border)method, if the view component is an instance ofjavax.swing.JComponent, otherwise this method is a no-op.voidsetGlassPane(JPanel glassPane) Sets theJLayer's glassPane component, which can benull.voidsetLayerEventMask(long layerEventMask) Enables the events from JLayer and all its descendants defined by the specified event mask parameter to be delivered to theLayerUI.eventDispatched(AWTEvent, JLayer)method.voidsetLayout(LayoutManager mgr) Sets the layout manager for this container.voidSets theLayerUIwhich will perform painting and receive input events for thisJLayer.voidSets theJLayer's view component, which can benull.voidupdateUI()Delegates its functionality to theLayerUI.updateUI(JLayer)method, ifLayerUIis set.Methods declared in class javax.swing.JComponentaddAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, 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, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods declared in class java.awt.Containeradd, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, 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, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusDownCycle, validate, validateTreeMethods declared in class java.awt.Componentaction, 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, 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, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, 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, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
- 
Constructor Details- 
JLayerpublic JLayer()
- 
JLayerCreates a newJLayerobject with defaultLayerUI.- Parameters:
- view- the component to be decorated by this- JLayer
- See Also:
 
- 
JLayerCreates a newJLayerobject with the specified view component andLayerUIobject.- Parameters:
- view- the component to be decorated
- ui- the- LayerUIdelegate to be used by this- JLayer
 
 
- 
- 
Method Details- 
getViewReturns theJLayer's view component ornull.
 This is a bound property.- Returns:
- the JLayer's view component ornullif none exists
- See Also:
 
- 
setViewSets theJLayer's view component, which can benull.
 This is a bound property.- Parameters:
- view- the view component for this- JLayer
- See Also:
 
- 
setUISets theLayerUIwhich will perform painting and receive input events for thisJLayer.- Parameters:
- ui- the- LayerUIfor this- JLayer
 
- 
getUIReturns theLayerUIfor thisJLayer.- Overrides:
- getUIin class- JComponent
- Returns:
- the LayerUIfor thisJLayer
 
- 
getGlassPaneReturns theJLayer's glassPane component ornull.
 This is a bound property.- Returns:
- the JLayer's glassPane component ornullif none exists
- See Also:
 
- 
setGlassPaneSets theJLayer's glassPane component, which can benull.
 This is a bound property.- Parameters:
- glassPane- the glassPane component of this- JLayer
- See Also:
 
- 
createGlassPaneCalled by the constructor methods to create a defaultglassPane. By default this method creates a new JPanel with visibility set to true and opacity set to false.- Returns:
- the default glassPane
 
- 
setLayoutSets the layout manager for this container. This method is overridden to prevent the layout manager from being set.Note: If mgris non-null, this method will throw an exception as layout managers are not supported on aJLayer.- Overrides:
- setLayoutin class- Container
- Parameters:
- mgr- the specified layout manager
- Throws:
- IllegalArgumentException- this method is not supported
- See Also:
 
- 
setBorderDelegates its functionality to thegetView().setBorder(Border)method, if the view component is an instance ofjavax.swing.JComponent, otherwise this method is a no-op.- Overrides:
- setBorderin class- JComponent
- Parameters:
- border- the border to be rendered for the- viewcomponent
- See Also:
 
- 
getBorderDelegates its functionality to thegetView().getBorder()method, if the view component is an instance ofjavax.swing.JComponent, otherwise returnsnull.- Overrides:
- getBorderin class- JComponent
- Returns:
- the border object for the viewcomponent
- See Also:
 
- 
addImplThis method is not supported byJLayerand always throwsUnsupportedOperationException- Overrides:
- addImplin 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- -1means append to the end
- Throws:
- UnsupportedOperationException- this method is not supported
- See Also:
 
- 
isPaintingOriginprotected boolean isPaintingOrigin()Always returnstrueto cause painting to originate fromJLayer, or one of its ancestors.- Overrides:
- isPaintingOriginin class- JComponent
- Returns:
- true
- See Also:
 
- 
paintImmediatelypublic void paintImmediately(int x, int y, int w, int h) Delegates its functionality to theLayerUI.paintImmediately(int, int, int, int, JLayer)method, ifLayerUIis set.- Overrides:
- paintImmediatelyin class- JComponent
- Parameters:
- x- the x value of the region to be painted
- y- the y value of the region to be painted
- w- the width of the region to be painted
- h- the height of the region to be painted
- See Also:
 
- 
imageUpdateDelegates its functionality to theLayerUI.imageUpdate(java.awt.Image, int, int, int, int, int, JLayer)method, if theLayerUIis set.- Specified by:
- imageUpdatein interface- ImageObserver
- Overrides:
- imageUpdatein class- Component
- Parameters:
- img- the image being observed
- infoflags- see- imageUpdatefor more information
- x- the x coordinate
- y- the y coordinate
- w- the width
- h- the height
- Returns:
- falseif the infoflags indicate that the image is completely loaded;- trueotherwise.
- See Also:
- 
- ImageObserver
- Graphics.drawImage(Image, int, int, Color, java.awt.image.ImageObserver)
- Graphics.drawImage(Image, int, int, java.awt.image.ImageObserver)
- Graphics.drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)
- Graphics.drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)
- ImageObserver.imageUpdate(java.awt.Image, int, int, int, int, int)
 
 
- 
paintDelegates all painting to theLayerUIobject.- Overrides:
- paintin class- JComponent
- Parameters:
- g- the- Graphicsto render to
- See Also:
 
- 
paintComponentThis method is empty, because all painting is done bypaint(Graphics)andComponentUI.update(Graphics, JComponent)methods- Overrides:
- paintComponentin class- JComponent
- Parameters:
- g- the- Graphicsobject to protect
- See Also:
 
- 
isOptimizedDrawingEnabledpublic boolean isOptimizedDrawingEnabled()TheJLayeroverrides the default implementation of this method (inJComponent) to returnfalse. This ensures that the drawing machinery will call theJLayer'spaintimplementation rather than messaging theJLayer's children directly.- Overrides:
- isOptimizedDrawingEnabledin class- JComponent
- Returns:
- false
 
- 
propertyChangeThis method gets called when a bound property is changed.- Specified by:
- propertyChangein interface- PropertyChangeListener
- Parameters:
- evt- A PropertyChangeEvent object describing the event source and the property that has changed.
 
- 
setLayerEventMaskpublic void setLayerEventMask(long layerEventMask) Enables the events from JLayer and all its descendants defined by the specified event mask parameter to be delivered to theLayerUI.eventDispatched(AWTEvent, JLayer)method.Events are delivered provided that LayerUIis set for thisJLayerand theJLayeris displayable.The following example shows how to correctly use this method in the LayerUIimplementations: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 defaultJLayerreceives no events and its event mask is0.- Parameters:
- layerEventMask- the bitmask of event types to receive
- See Also:
 
- 
getLayerEventMaskpublic long getLayerEventMask()Returns the bitmap of event mask to receive by thisJLayerand itsLayerUI.It means that LayerUI.eventDispatched(AWTEvent, JLayer)method will only receive events that match the event mask.By default JLayerreceives no events.- Returns:
- the bitmask of event types to receive for this JLayer
 
- 
updateUIpublic void updateUI()Delegates its functionality to theLayerUI.updateUI(JLayer)method, ifLayerUIis set.- Overrides:
- updateUIin class- JComponent
- See Also:
 
- 
getPreferredScrollableViewportSizeReturns the preferred size of the viewport for a view component.If the view component of this layer implements Scrollable, this method delegates its implementation to the view component.- Specified by:
- getPreferredScrollableViewportSizein interface- Scrollable
- Returns:
- the preferred size of the viewport for a view component
- See Also:
 
- 
getScrollableBlockIncrementReturns 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 view component of this layer implements Scrollable, this method delegates its implementation to the view component.- Specified by:
- getScrollableBlockIncrementin 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:
 
- 
getScrollableTracksViewportHeightpublic boolean getScrollableTracksViewportHeight()Returnsfalseto 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 view component of this layer implements Scrollable, this method delegates its implementation to the view component.- Specified by:
- getScrollableTracksViewportHeightin interface- Scrollable
- Returns:
- whether the layer should track the height of the viewport
- See Also:
 
- 
getScrollableTracksViewportWidthpublic boolean getScrollableTracksViewportWidth()Returnsfalseto 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 view component of this layer implements Scrollable, this method delegates its implementation to the view component.- Specified by:
- getScrollableTracksViewportWidthin interface- Scrollable
- Returns:
- whether the layer should track the width of the viewport
- See Also:
 
- 
getScrollableUnitIncrementReturns 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 view component of this layer implements Scrollable, this method delegates its implementation to the view component.- Specified by:
- getScrollableUnitIncrementin 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:
 
- 
doLayoutpublic void doLayout()Delegates its functionality to theLayerUI.doLayout(JLayer)method, ifLayerUIis set.
- 
getAccessibleContextGets the AccessibleContext associated with thisJLayer.- Specified by:
- getAccessibleContextin interface- Accessible
- Overrides:
- getAccessibleContextin class- Component
- Returns:
- the AccessibleContext associated with this JLayer.
 
 
-