JavaFX Spinner empty text nullpointerexception

前端 未结 4 2084
旧巷少年郎
旧巷少年郎 2021-01-11 16:40

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

相关标签:
4条回答
  • 2021-01-11 17:04

    I would consider this a bug: the IntegerSpinnerValueFactory should properly handle this case.

    One workaround is to provide a converter to the spinner value factory that evaluates to a default value if the text value is not valid:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Spinner;
    import javafx.scene.control.SpinnerValueFactory.IntegerSpinnerValueFactory;
    import javafx.stage.Stage;
    import javafx.util.StringConverter;
    
    public class Test extends Application {
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage aPrimaryStage) throws Exception {
            IntegerSpinnerValueFactory valueFactory = new IntegerSpinnerValueFactory(0, 10);
    
            valueFactory.setConverter(new StringConverter<Integer>() {
    
                @Override
                public String toString(Integer object) {
                    return object.toString() ;
                }
    
                @Override
                public Integer fromString(String string) {
                    if (string.matches("-?\\d+")) {
                        return new Integer(string);
                    }
                    // default to 0:
                    return 0 ;
                }
    
            });
    
            Spinner<Integer> spinner = new Spinner<>(valueFactory);
            spinner.setEditable(true);
            aPrimaryStage.setScene(new Scene(spinner));
            aPrimaryStage.show();
        }
    }
    
    0 讨论(0)
  • 2021-01-11 17:05

    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<Integer> 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;

    0 讨论(0)
  • 2021-01-11 17:11

    I had a rummage through the JDK source.

    The NPE is thrown from if (newValue < getMin()) { in the listener lambda here:

    javafx.scene.control.SpinnerValueFactory.java

        public IntegerSpinnerValueFactory(@NamedArg("min") int min,
                                          @NamedArg("max") int max,
                                          @NamedArg("initialValue") int initialValue,
                                          @NamedArg("amountToStepBy") int amountToStepBy) {
            setMin(min);
            setMax(max);
            setAmountToStepBy(amountToStepBy);
            setConverter(new IntegerStringConverter());
    
            valueProperty().addListener((o, oldValue, newValue) -> {
                // when the value is set, we need to react to ensure it is a
                // valid value (and if not, blow up appropriately)
                if (newValue < getMin()) { 
                    setValue(getMin());
                } else if (newValue > getMax()) {
                    setValue(getMax());
                }
            });
            setValue(initialValue >= min && initialValue <= max ? initialValue : min);
        }
    

    presumably newValue is null and the auto unboxing of null throws NPE. As the input comes from the editor, I suspect the IntegerStringConverter which is the default converter.

    Looking at the implementation here:

    javafx.util.converter.IntegerStringConverter

    public class IntegerStringConverter extends StringConverter<Integer> {
        /** {@inheritDoc} */
        @Override public Integer fromString(String value) {
            // If the specified value is null or zero-length, return null
            if (value == null) {
                return null;
            }
    
            value = value.trim();
    
            if (value.length() < 1) {
                return null;
            }
    
            return Integer.valueOf(value);
        }
    
        /** {@inheritDoc} */
        @Override public String toString(Integer value) {
            // If the specified value is null, return a zero-length String
            if (value == null) {
                return "";
            }
    
            return (Integer.toString(((Integer)value).intValue()));
        }
    }
    

    We see that it will happily return null for the empty string, which is kind of reasonable given that there exists no valid value for the input.

    Tracing up the call stack I find where the value is coming from:

    javafx.scene.control.Spinner

    public Spinner() {
        getStyleClass().add(DEFAULT_STYLE_CLASS);
        setAccessibleRole(AccessibleRole.SPINNER);
    
        getEditor().setOnAction(action -> {
            String text = getEditor().getText();
            SpinnerValueFactory<T> valueFactory = getValueFactory();
            if (valueFactory != null) {
                StringConverter<T> converter = valueFactory.getConverter();
                if (converter != null) {
                    T value = converter.fromString(text);
                    valueFactory.setValue(value);
                }
            }
        });
    

    The value is set with the value obtained from the converter T value = converter.fromString(text); which presumably is null. At this point I believe that the spinner class should check that value is not null and if it is restore the previous value to the editor.

    I am now fairly sure that this is a bug. Moreover I don't think that a work around with a converter that never returns null is going to work properly as it will only mask the problem and what value should be returned when the value cannot be converted?

    Edit: Workaround

    Replacing the onAction of the spinner editor to reject invalid input with a "return to valid" policy fixes the issue:

    public static <T> void fixSpinner2(Spinner<T> aSpinner) {
        aSpinner.getEditor().setOnAction(action -> {
            String text = aSpinner.getEditor().getText();
            SpinnerValueFactory<T> factory = aSpinner.getValueFactory();
            if (factory != null) {
                StringConverter<T> converter = factory.getConverter();
                if (converter != null) {
                    T value = converter.fromString(text);
                    if (null != value) {
                        factory.setValue(value);
                    }
                    else {
                        aSpinner.getEditor().setText(converter.toString(factory.getValue()));
                    }
                }
            }
            action.consume();
        });
    }
    

    As opposed to a listener on the valueProperty this avoids triggering other listeners with invalid data. However this highlights another issue in the spinner class. While the above fixes the issue by returning to a valid value on pressing enter. Erasing the input without committing (pressing enter) and then pressing increment or decrement will cause the same NPE but with slightly different call stack.

    Cause:

    public void increment(int steps) {
        SpinnerValueFactory<T> valueFactory = getValueFactory();
        if (valueFactory == null) {
            throw new IllegalStateException("Can't increment Spinner with a null SpinnerValueFactory");
        }
        commitEditorText();
        valueFactory.increment(steps);
    }
    

    Decrement is similar, both call into commitEditorText below:

    private void commitEditorText() {
        if (!isEditable()) return;
        String text = getEditor().getText();
        SpinnerValueFactory<T> valueFactory = getValueFactory();
        if (valueFactory != null) {
            StringConverter<T> converter = valueFactory.getConverter();
            if (converter != null) {
                T value = converter.fromString(text);
                valueFactory.setValue(value);
            }
        }
    }
    

    Notice the copy-paste from the onAction in the constructor:

        getEditor().setOnAction(action -> {
            String text = getEditor().getText();
            SpinnerValueFactory<T> valueFactory = getValueFactory();
            if (valueFactory != null) {
                StringConverter<T> converter = valueFactory.getConverter();
                if (converter != null) {
                    T value = converter.fromString(text);
                    valueFactory.setValue(value);
                }
            }
        });
    

    I believe that commitEditorText should be changed to trigger onAction on the editor instead like so:

    private void commitEditorText() {
        if (!isEditable()) return;
        getEditor().getOnAction().handle(new ActionEvent(this, this));
    }
    

    then the behavior would be consistent and give the editor a chance to handle the input before it goes to the value factory.

    0 讨论(0)
  • 2021-01-11 17:16

    It's a known bug which is fixed in Java 9 - see https://bugs.openjdk.java.net/browse/JDK-8150962

    0 讨论(0)
提交回复
热议问题