Re: Two Questions: JSpinner and datatype
On 5/17/2010 8:37 AM, 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
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
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 is just like `new SpinnerNumberModel(1, 1, 20, 1)' -- the
fact that your promoted-to-int arguments happen to be in range for
`short' (or even for `byte') doesn't influence the constructor's
behavior, nor that of the constructed SpinnerNumberModel.
Also, even if the supposed range of the SpinnerNumberModel is
1 through 20 with an integer step, setValue(new Double(98.6)) is
still possible and will work.
It's a little odd that you use getValue() instead of getNumber(),
but that shouldn't matter a lot.
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
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.
You can use getClass() or instanceof on the returned Object().
If you really want to be draconian, you could do
Number num = seasonNumberModel.getNumber();
if (! (num instanceof Short)) {
// Accept no substitutes:
num = Short.valueOf(num.shortValue());
}
--
Eric Sosman
esosman@ieee-dot-org.invalid