Question

I have a JSpinner with SpinnerNumberModel (1, Double.MIN_VALUE, Double.MAX_VALUE, 0.01)

If I type directly to JSpinner - 1000, click OK in some dialog, and get spinner.getValue() it will return '1' instead of 1000.

If I type 1000 and change focus to somewhere else like clicking on JDialog's emty space and read value after that it will be correct=1000. If I will change values with spinner's arrows - value will be correct too.

How to fix Jspinner so it will support typing values without changing focus to somewhere else first before getting it's value?

Java JDK 1.6.0_23

Was it helpful?

Solution

The JSpinner JavaDoc describes why this happens and how to solve it.

A JSpinner has a single child component that's responsible for displaying and potentially changing the current element or value of the model, which is called the editor. The editor is created by the JSpinner's constructor and can be changed with the editor property. The JSpinner's editor stays in sync with the model by listening for ChangeEvents. If the user has changed the value displayed by the editor it is possible for the model's value to differ from that of the editor. To make sure the model has the same value as the editor use the commitEdit method, eg:

try {
    spinner.commitEdit();
}
catch (ParseException pe) {{
    // Edited value is invalid, spinner.getValue() will return
    // the last valid value, you could revert the spinner to show that:
    JComponent editor = spinner.getEditor()
    if (editor instanceof DefaultEditor) {
        ((DefaultEditor)editor).getTextField().setValue(spinner.getValue();
    }
    // reset the value to some known value:
    spinner.setValue(fallbackValue);
    // or treat the last valid value as the current, in which
    // case you don't need to do anything.
}
return spinner.getValue();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top