I have an issue where an editable JavaFX 8 Spinner
causes an uncaught NullPointerException
if one clears the editor text and commits and then click
This is correct and expected behavior for an Integer based Spinner control.
You should either set its Editable property to false, if you do not wish users to edit the values set via the Factory.
Or you should be handling the event raised by the spinner's value property.
Here's a simple example of how to do so:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.SpinnerValueFactory.IntegerSpinnerValueFactory;
import javafx.stage.Stage;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
public class Spin extends Application {
Spinner spinner;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage aPrimaryStage) throws Exception {
IntegerSpinnerValueFactory valueFactory = new IntegerSpinnerValueFactory(0, 10);
spinner = new Spinner<>(valueFactory);
spinner.setEditable(true);
spinner.valueProperty().addListener((observableValue, oldValue, newValue) -> handleSpin(observableValue, oldValue, newValue));
aPrimaryStage.setScene(new Scene(spinner));
aPrimaryStage.show();
}
private void handleSpin(ObservableValue> observableValue, Number oldValue, Number newValue) {
try {
if (newValue == null) {
spinner.getValueFactory().setValue((int)oldValue);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
This may also assist you, if you wish to use a converter class to help in handling the changes more comprehensively.
See also the official documentation on the setEditable method;