Re: Two Questions: JSpinner and datatype
Rhino wrote:
1. If I create a JSpinner with a SpinnerNumberModel and specify the numbers
in the model explicitly as short, why can't I rely on the getValue() from
the JSpinner always returning shorts? In other words, if I define it all
Because that is not the defined behavior of the model.
with shorts, what actions on my part will result in getValue() returning an
Integer or something other than Short? For some reason, the results from
I don't know, but I bet if you look at the source for
'SpinnerNumberModel' you'll find out. My guess is that it uses the
subtype of 'Number' that most closely matches the returned value.
Given the model class's contract, there's nothing you can do directly
to change what it returns. You get a 'Number' and that's the best you
can predict.
getValue() are sometimes Short but sometimes Integer and I don't understand
why. I'm trying to figure out how to make getValue() return ONLY Short (or,
failing that, to return only Integer.) This is the statement that defined
the model:
SpinnerNumberModel seasonNumberModel = new SpinnerNumberModel((short)1,
(short)1, (short)20, (short)1);
This call feeds integers to the constructor. Did you look at the
Javadocs for the constructor? You are taking 'int' values, casting
them to 'short', then the language is widening them back to 'int'
arguments. There is no constructor overload for that class that takes
'short' parameters.
All you are guaranteed from 'SpinnerNumberModel' is that the returned
value of 'getValue()' is a 'Number'. (The signature says 'Object',
but the Javadocs tell you that it will be a 'Number'.) If you want
different behavior, set your own model.
2. If a given method can return various sorts of integer numbers, like
Short, Integer, and Long, what is the simplest way to determine the exact
type that is being returned by the method? I'm just trying to cover the
Don't.
Just use the return type, which for 'SpinnerNumberModel' is an
'Object' that can be downcast to 'Number'.
worst-case scenario that factors beyond my control may make it impossible
to predict whether getValue() is going to return Integer or Short from my
JSpinner. If that turns out to be true, I'd like to know the best way to
determine if a given value is a short, int, long or anything else. I think
I used to know how to do that several years ago but I'm darned if I can
remember that technique now.
'instanceof'?
What difference does it make? Just use 'Number'. Use its
'longValue()', 'intValue()', etc., methods if you must.
You're making a mountain out of a molehill. Read the Javadocs for the
classes and methods you're using! They will tell you what guarantees
you can count on, and that's all you get to count on. Live with it.
--
Lew