确定谁调用stateChanged

时间:2013-05-20 06:11:40

标签: java swing model-view-controller actionlistener changelistener

我有一些看起来像这样的滑块:

//Create the slider
    JSlider speedSlider = new JSlider(JSlider.VERTICAL, MIN_SPEED, MAX_SPEED, initValue);
    speedSlider.addChangeListener(controller);
    speedSlider.setMajorTickSpacing(MAJOR_TICK_SPACING);
    speedSlider.setPaintTicks(true);

    panel.add(speedSlider);

在我的View.java类

有Controller.java

public class Controller implements ControllerInterface {

    //...

    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider)e.getSource();
        if (!source.getValueIsAdjusting()) {
            int speed = (int)source.getValue();
            if (0 == speed) {
                // stop
            }
            else {
                model.setSpeedBody(speed);
            }
        }
    }
}

问题在于我无法确定滑块事件究竟是什么,怎么做? (ControllerInterface扩展了ChangeListener)

1 个答案:

答案 0 :(得分:2)

测试来源的价值:

JSlider source = (JSlider)e.getSource();
if (source == speedSlider) {
    ...
}
else if (source == gearSlider) {
    ...
}

或者为每个滑块添加一个特定的侦听器,以便每个侦听器只通知一个滑块的更改:

speedSlider.addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        ...
    }
});