从侦听器对象接收事件


如何

注册以接收侦听器对象的事件的通知?

从本质上讲,我想要实现的目标可以通过以下方式可视化:

this.mouseMoved(( = listener.mouseMoved((

Class Secondary implements MouseMotionListener {
    public Secondary(MouseMotionListener listener) {
        // Here Secondary needs to be registered to the same observer that
        // listener is getting notified from so that the Secondary class's
        // mouseMoved() and mouseDragged() both fire at the same time and 
        // with the same MouseEvents as the listener's.
    }
    @Override
    void mouseMoved(MouseEvent e) {
        // This needs to be essentially the same as the events fired
        // in the constructor's parameter object
    }
    @Override
    void mouseDragged(MouseEvent e) {
        // This needs to be essentially the same as the events fired
        // in the constructor's parameter object
    }
}

侦听器由调用方法的人触发,JComponents 接受鼠标侦听器作为参数,因此您必须设置它:

JPanel panel = new JPanel();
jFrame.add(panel);
panel.addMouseListener(new Secondary());

如果要调度事件,可以使用委托模式。

class Secondary implements MouseMotionListener {
MouseMotionListener other;
public Secondary(MouseMotionListener listener) {
    other = listener;
}
@Override
void mouseMoved(MouseEvent e) {
    other.mouseMoved(e);
}
@Override
void mouseDragged(MouseEvent e) {
    other.mouseDragged(e);
}
}

最新更新