JavaFX Integer Spinner (IntegerSpinnerValueFactory) does not wrap around the value to minimum

Venkata Raju :

I have created an Integer Spinner with values

min (5), max (15) and initialValue (12) and wrapAround (true).

Once the spinner reaches the max (15) value during increment, instead of resetting the value to min (5) as it says in the documentation, it is being reset to value 10 (max (15) - min (5))

public final void setWrapAround​(boolean value)

Sets the value of the property wrapAround.

Property description:

The wrapAround property is used to specify whether the value factory should be circular. For example, should an integer-based value model increment from the maximum value back to the minimum value (and vice versa).

Note: Decrement works properly, once it reaches the min (5) value, Spinner value automatically set to max (15)

public class IntSpinnerTest extends Application
{
  @Override
  public void start(Stage stage) throws Exception
  {
    var spinner = new Spinner<Integer>();

    var factory = new SpinnerValueFactory.IntegerSpinnerValueFactory(5, 15, 12);
    factory.setWrapAround(true);

    spinner.setValueFactory(factory);

    stage.setScene(new Scene(new BorderPane(spinner), 400, 200));

    stage.setTitle("IntSpinnerTest");
    stage.centerOnScreen();
    stage.show();
  }

  public static void main(String[] args)
  {
    launch(args);
  }
}
Slaw :

This is a known bug: JDK-8193286. The submitter included a workaround—subclassing IntegerSpinnerValueFactory:

package sample; 

import javafx.scene.control.SpinnerValueFactory.IntegerSpinnerValueFactory; 

public final class IntSpinnerValueFactory extends IntegerSpinnerValueFactory { 

  public IntSpinnerValueFactory(final int min, final int max) { 
    super(min, max); 
  } 

  public IntSpinnerValueFactory(final int min, final int max, final int initialValue) { 
    super(min, max, initialValue, 1); 
  } 

  @Override 
  public void increment(final int steps) { 
    final int min = getMin(); 
    final int max = getMax(); 
    final int currentValue = getValue(); 
    final int newIndex = currentValue + steps * getAmountToStepBy(); 
    setValue(newIndex <= max ? newIndex : (isWrapAround() ? (newIndex - min) % (max - min + 1) + min : max)); 
  } 

} 

Note: Workaround has been slightly modified based on recommendations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=80886&siteId=1