如何在java中用事件监听器切换对象?

时间:2013-06-27 08:59:48

标签: java events object listener

我需要你的帮助。我正在制作一个使用Wiimote的控制程序,我需要制作两种不同类型的控件。每个控制器代码都在类controlType1和controlType2中定义(此处不包括#2,但大多数情况与#1相同)。

我的想法是,当我按下WiiMote上的某个按钮时,控制器从type1切换到type2。我实例化了2个对象,它应该在按下按钮时删除其中一个对象的侦听器,并将其更改为另一个对象。

目前,我已经走了这么远而被困在这里。知道我该怎么办?

public class WiiDroneControl implements ControlSwitchListener {

private Wiimote wiimote;

private WiimoteListener control1 = (WiimoteListener) new controlType1(this);
private WiimoteListener control2 = (WiimoteListener) new controlType2(this);

public WiiDroneControl() {

    Wiimote wiimotes[] = WiiUseApiManager.getWiimotes(1, true);

    if(wiimotes!= null && wiimotes.length > 0)
    {
        wiimote = wiimotes[0];

        wiimote.addWiiMoteEventListeners(control1);
        wiimote.addWiiMoteEventListeners(control2);

        wiimote.activateMotionSensing();
        wiimote.activateContinuous();
        wiimote.getStatus();
    }
}

@Override
public void onSwitchEvent() {
    // TODO Auto-generated method stub

}
}

另一个班级

public class controlType1 implements WiimoteListener{

ControlSwitchListener listener = null;

public controlType1(ControlSwitchListener l) {
    listener = l;
}

@Override
public void onButtonsEvent(WiimoteButtonsEvent e) {
    // TODO Auto-generated method stub
    listener.onSwitchEvent();

    if (e.isButtonOnePressed())
    {
        //switch controller object when this button is pressed
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题......

    public class WiiDroneControl implements ControlSwitchListener {

    private Wiimote wiimote;
    private WiimoteListener control1 =  new controlType1(this);
    private WiimoteListener control2 =  new controlType2(this);
    private WiimoteListener current = control1;

    public WiiDroneControl() {

        Wiimote wiimotes[] = WiiUseApiManager.getWiimotes(1, true);

        if(wiimotes!= null && wiimotes.length > 0)
        {
            wiimote = wiimotes[0];
            wiimote.addWiiMoteEventListeners(current);

            wiimote.activateMotionSensing();
            wiimote.activateContinuous();
            wiimote.getStatus();
        }
    }

    @Override
    public void onSwitchEvent() {
        current = current.equals(control1) ? control2 : control1;
    }
}