1

我在我的 Java GUI 中使用 jLayeredPane。我在我的 jLayeredPane 的 DEFAULT_LAYER 上添加了一些面板(jPanelsLayer1),并且每个 jPanel 都有一个 MouseAdapter 覆盖 mouseEntered 和 mouseExited 用于我的目的。当我在 JlayerdePane 的 PALETTE_LAYER 上,在 jPanelsLayer1 的顶部添加另一个组件(jPanelsLayer2)并为它们定义 MouseAdapter 时,我遇到了问题。当鼠标进入公共区域时,不同层的jPanel的mouseEntered和mouseExited连续运行几次。我只希望 jPanelslayer2 mouseAdapters 在 jpanelLayer1 顶部看到时处于活动状态。也许一个解决方案是删除 jPanelLayer1 mouseAdapter。但这并不有效。

请指导我.....sajad

4

1 回答 1

3

我不确定您的问题出在哪里,因为当我对其进行测试时,即使“调色板”面板位于“默认”面板上方,鼠标也仅在“调色板”面板上方时才在“调色板”面板中处于活动状态。例如,这是我的SSCCE来测试这个概念。随意修改它以向我们展示您的问题:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class LayeredFun extends JLayeredPane {
   private static final int JLP_WIDTH = 400;
   private static final int JLP_HEIGHT = 400;
   private static final Dimension PANEL_SIZE = new Dimension(200, 200);

   public LayeredFun() {
      JPanel defaultPanel = createPanel("Default Panel", new Point(10, 10), Color.cyan);
      JPanel palettePanel = createPanel("Palette Panel", new Point(100, 100), Color.pink);

      add(defaultPanel, JLayeredPane.DEFAULT_LAYER);
      add(palettePanel, JLayeredPane.PALETTE_LAYER);
   }

   private JPanel createPanel(String name, Point location, Color color) {
      JPanel defaultPanel = new JPanel();
      defaultPanel.setSize(PANEL_SIZE);
      defaultPanel.setLocation(location);
      MyMouseAdapter defaultMouseAdapater = new MyMouseAdapter(name);
      defaultPanel.addMouseListener(defaultMouseAdapater);
      defaultPanel.addMouseMotionListener(defaultMouseAdapater);
      defaultPanel.setBackground(color);
      defaultPanel.setBorder(BorderFactory.createTitledBorder(name));
      return defaultPanel;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(JLP_WIDTH, JLP_HEIGHT);
   }

   private class MyMouseAdapter extends MouseAdapter {
      private String name;

      public MyMouseAdapter(String name) {
         this.name = name;
      }

      @Override
      public void mouseEntered(MouseEvent e) {
         System.out.printf("%s: mouseEntered%n", name);
      }

      @Override
      public void mouseExited(MouseEvent e) {
         System.out.printf("%s: mouseExited%n", name);
      }

      @Override
      public void mouseMoved(MouseEvent e) {
         System.out.printf("%s: mouseMoved%n", name);
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("LayeredFun");
      frame.getContentPane().add(new LayeredFun());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
于 2011-06-23T13:56:02.253 回答