1

我在我的 JFrame 中添加了一个 MouseMotionListener 来控制从我的 jframe 中的所有对象到达的所有鼠标运动消息,但是当我将鼠标移到 JLayeredPane 上时,不会产生任何消息。请帮我在我的 JFrame 中添加一个中央 MouseMotionListener 来控制来自其中所有对象的所有消息。

太谢谢了。

4

2 回答 2

3

下面是递归地将 MouseMotionListener 添加到所有组件的代码。请注意,为了处理生成的 MouseEvents,您需要使用 SwingUtilities 将 Point 从特定 Component 的空间转换到 JFrame 的空间。

public static void installMouseMotionListenerOnAll(Component c, MouseMotionListener mml) {
  c.addMouseMotionListener(mml);
  if (c instanceof Container) {
    for (Component child : ((Container)c).getComponents()) {
      installMouseMotionListenerOnAll(child, mml);
    }
  }
}
于 2016-05-27T14:23:54.650 回答
2

您可能希望使用 AWTEventListener 来侦听所有 AWT 消息。

下面的代码展示了如何监听鼠标和按键事件:

long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK
    + AWTEvent.MOUSE_EVENT_MASK
    + AWTEvent.KEY_EVENT_MASK;

Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener()
{
    public void eventDispatched(AWTEvent e)
    {
        System.out.println(e.getID());
    }
}, eventMask);

有关详细信息,请参阅全局事件侦听器

于 2016-05-27T15:06:11.140 回答