Question

I used the code below when initialising my sliders:

//Gets the corresponding slider value, from it's represented value. 
int curr = valueToSlider(min, max, current, scale, q, grains); 

final JSlider slider = new JSlider(JSlider.VERTICAL, 0, grains, curr);

slider.addChangeListener(new ChangeListener() {

  public void stateChanged(ChangeEvent event) {
    double value = sliderToValue(min, max, slider.getValue(), scale, q, grains); 
    String str = ""; 

    if (valueType == SliderValueType.FLOAT) 
       str = String.format("%.2f",value);
    if (valueType == SliderValueType.INTEGER) 
       str = String.format("%.0f", value); 

    valueLabel.setText(str); 
    callCommand(c, value);
  }
});

Now I need to trigger the changed event to get that valueLabel label to set in its correct format.

slider.setValue(curr); 

That doesn't trigger the changed event, I'm guessing because the value hasn't changed. A simple hacky fix is to just do something like:

slider.setValue(1);
slider.setValue(curr);

But you could imagine that in some code, that triggering the changed event with a random value, might have unwanted consequences.

I could reproduce that setText method in my initialisation method.

if (valueType == SliderValueType.FLOAT) 
   str = String.format("%.2f",curr);

if (valueType == SliderValueType.INTEGER) 
   str = String.format("%.0f", curr); 

valueLabel.setText(str);

(Which sounds like the best solution here to be honest).

But just wondering - is there a way to trigger an changed event another way?

Was it helpful?

Solution

Refactor the contents of stateChanged() into a separate method, say updateLabel(). Call that method from both the stateChanged() method and your initialisation code.

I agree, it would be wrong to set the value to some arbitrary value just to trigger a change.

Note: you can manually trigger a change through JSlider.fireStateChanged(), however that's still less clear to a future code maintainer than simply calling updateLabel().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top