Being tripped up by the JavaFX Spinner
2016-05-03
Published:While working on converting MinStory to use JavaFX instead of Swing, I got stuck for quite a while implementing a dialog using the Spinner from JavaFX.
When I saved the information the user had entered in the GUI, the information seemed to be lost, and reverted to the information it had contained when it was instantiated. I was thinking it had something to do with the GUI being loaded from an fxml-file - that the controller was working with a different object than the one I thought it was working with.
Then I noticed that all the information was being saved correctly, except the values of the Spinner. After spending some time looking through the API and searching to see if I was using it correctly, I finally found the answer.
When I read the API documentation for the JavaFX Spinner closely (confirming something that appeared in an earlier search), I found the following at the very end:
If the user has changed the value displayed in the editor it is possible for the Spinner value to differ from that of the editor. To make sure the model has the same value as the editor, the user must commit the edit using the Enter key.
In other words, unless the user has pressed the Enter key after writing something in the TextField associated with the Spinner, the information displayed in it is not the same as the information actually used by the Spinner.
In my opinion, this violates the principle of least astonishment, both for the programmer and the user.
I ended up using the following to get the value of the TextField:
spinner.getValueFactory().getConverter().fromString(spinner.getEditor().getText());
That way, if the user has moved the Spinner to get the value, the TextField should have the same value as the Spinner itself. If the user has written something in the TextField, that would be the value the user expects to see, and is what he/she will get.
If the user has entered something that is not a valid value for the Spinner, the above code will throw an exception.