Detecting Events
JLayer and LayerUI work together to detect different kinds of events occurring over any part of the view (including nested subcomponents). These classes collectively provide four methods that make event detection possible:
- public void setLayerEventMask(long layerEventMask): This JLayer method must be called with a bitmask of AWTEvent constants to select those event types that are to be detected. Example: setLayerEventMask (AWTEvent.KEY_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK); allows key events and focus change events to be detected.
- public void installUI(JComponent c): This LayerUI method is the place to begin event detection by invoking setLayerEventMask(). Code within this method first invokes the superclass method (super.installUI (c);), then casts the JComponent argument, which references the JLayer, to JLayer, and finally uses the result of the cast to invoke setLayerEventMask(): ((JLayer) c).setLayerEventMask(AWTEvent.KEY_EVENT_MASK);, for example.
- public void uninstallUI(JComponent c): This LayerUI method is the place to end event detection by invoking setLayerEventMask() with a 0 argument. Code within this method first invokes the superclass method (super.uninstallUI (c);), then casts the JComponent argument, which references the JLayer, to JLayer, and finally uses the result of the cast to invoke setLayerEventMask(): ((JLayer) c).setLayerEventMask(0);.
- public void eventDispatched(AWTEvent e, Jlayer<? extends V> l): This LayerUI method is invoked whenever one of the previously registered event types occurs. Place code in this method to respond to the event and update the layer as appropriate. After updating various painting attributes (such as color), invoke repaint() via the JLayer argument that's passed to this method to repaint the view.
In Listing 2, LayerUI's installUI() method invokes setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK) to allow detection of mouse motion events, which result in calls to the eventDispatched() method.
This method first invokes the javax.swing.SwingUtilities class's convertPoint() method to ensure that the mouse motion event's coordinates are relative to the layer (they're relative to the component over which the mouse cursor hovers).
Next, the method tests if the mouse cursor is over brand text by checking if its coordinates lie within a rectangular region surrounding the UI's center. If the coordinates lie within this region, the brand's text color is changed to pale red; otherwise, it reverts to blue. The UI is redrawn.
Figure 2 reveals the UI before and after the mouse cursor is moved over the brand text.
Figure 2 Repainting the brand text in response to the mouse cursor moving over this text offers a subtle reminder to the user.