为多个JPanel注册1个mouseDragged事件

时间:2012-11-06 15:20:36

标签: java swing jpanel mouseevent mousemotionevent

我有一个主JPanel,上面还有另外两个JPanel(面板A和面板B),如下图所示:

enter image description here

我想跟踪这些JPanel上的mouseDragged事件,目前我正在为所有3个JPanel跟踪它:

mainPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
    public void mouseDragged(java.awt.event.MouseEvent evt) {

    }
});

panelA.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
    public void mouseDragged(java.awt.event.MouseEvent evt) {

    }
});

panelB.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
    public void mouseDragged(java.awt.event.MouseEvent evt) {

    }
});

有没有办法通过仅注册一个侦听器而不是3来跟踪所有3个JPanel的mouseDragged事件?谢谢

1 个答案:

答案 0 :(得分:3)

class MyMouseMotionListener implements MouseMotionListener{
    public void mouseDragged(java.awt.event.MouseEvent evt) {

    }
}

...

MouseMotionListener myListener = new MyMouseMotionListener();

mainPanel.addMouseMotionListener(myListener);
panelA.addMouseMotionListener(myListener);
panelB.addMouseMotionListener(myListener);