模块 java.desktop

类 JLayer<V extends Component >

类型参数:
V - JLayer 的视图组件的类型
所有已实现的接口:
ImageObserver , MenuContainer , PropertyChangeListener , Serializable , EventListener , Accessible , Scrollable

public final class JLayer<V extends Component > extends JComponent implements Scrollable , PropertyChangeListener , Accessible
JLayer 是 Swing 组件的通用装饰器,它使您能够实现各种高级绘画效果,并接收在其边界内生成的所有 AWTEvent 的通知。

JLayer 将绘画和输入事件的处理委托给 LayerUI 对象,该对象执行实际装饰。

LayerUI 中实现的自定义绘画和事件通知适用于 JLayer 本身及其所有子组件。这种组合使您能够通过添加新的高级功能来丰富现有组件,例如层次结构的临时锁定、复合组件的数据提示、增强的鼠标滚动等。

如果您只需要对复合组件进行自定义绘制或从其子组件捕获输入事件,JLayer 是一个很好的解决方案。

 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();
       }
     });
   }
 }
 
笔记:JLayer 不支持以下方法: 使用它们中的任何一个都会导致 UnsupportedOperationException 被抛出,将组件添加到 JLayer 使用 setView(Component) setGlassPane(JPanel)
自从:
1.7
参见: