JavaFX Spinner empty text nullpointerexception

前端 未结 4 2113
旧巷少年郎
旧巷少年郎 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() {
    
                @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 spinner = new Spinner<>(valueFactory);
            spinner.setEditable(true);
            aPrimaryStage.setScene(new Scene(spinner));
            aPrimaryStage.show();
        }
    }
    

提交回复
热议问题