Question

I have a few sliders that look like this:

//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);

in my View.java class

there is 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);
            }
        }
    }
}

The problem is that I can not determine from what it was exactly the slider event, how to do it? (ControllerInterface extends ChangeListener)

Was it helpful?

Solution

Test the value of the source:

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

Or add a specific listener to each slider, so that each listener is notified of the changes of just one slider:

speedSlider.addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        ...
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top