4

In my application some values internally have their range from 0. But user should see this range starting from 1. I thought it would be appropriate to move this offseting stuff into presentation. In this case it is JSpinner component. So that I could specify in contructor if there is an offset (not all values have it). But if I override getValue() of JSpinner or getValue() of model to be something like that (+1 is just for test)

       public Object getValue() {
            Number value = (Number)super.getValue();
            Number newValue=value;
            if (value instanceof Double){
                newValue=value.doubleValue()+1;
            }
            else if (value instanceof Integer){
                newValue = value.intValue()+1;
            }
            return newValue;
        }

it goes into infinite loop. I guess, it fires state change event for some reason here. Calls getValue again, increments more, fires event, increments and so on. How could this be solved? Thanks

Boris Mikhaylov
  • 329
  • 1
  • 12

2 Answers2

4

Don't mingle your program's data model and the spinner's number model; keep them separate. Delegate to a private SpinnerNumberModel having the correct presentation range, 1..n. Provide an accessor that returns values in the desired range, 0..n–1.

Provide the method getAdjustedValue(), which is basically getValue()-offset, that all clients should use instead of getValue()?

Yes. The SpinnerModel serves the JSpinner view. If your application's model uses different units, some transformation must occur. You'll have to decide where that makes most sense. As a concrete example, this model's ControlPanel has a spinner that adjusts a frequency in Hz, while the application's Timer requires a period in milliseconds.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • So, if there is an offset, JSpinner passes `value+offset` to `SpinnerNumberModel` and provides method `getAdjustedValue` which is basically `getValue()-offset`, which all clients should use instead of `getValue`? Did I understand you correct? – Boris Mikhaylov Oct 28 '11 at 01:57
2

I think that CyclingSpinnerListModel can do that

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Could you elaborate that? I don't see how it helps – Boris Mikhaylov Oct 27 '11 at 20:56
  • @Boris Mikhaylov that about `it goes into infinite loop.`, then you can restict that into some Range – mKorbel Oct 27 '11 at 20:59
  • +1 This is a good example of a private `SpinnerModel`, as suggested [here](http://stackoverflow.com/questions/7921689/java-how-do-i-make-jspinner-show-value-with-some-offset/7924274#7924274). – trashgod Oct 28 '11 at 01:35