Re: Two Questions: JSpinner and datatype
RedGrittyBrick <RedGrittyBrick@spamweary.invalid> wrote in
news:4bf14bfd$0$28004$db0fefd9@news.zen.co.uk:
On 17/05/2010 13:37, 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);
The relevant 1.6 API signature is SpinnerNumberModel(int value, int
minimum, int maximum, int stepSize) - there isn't a constructor for
shorts, so your shorts are being extended to ints by the compiler
before the constructor gets to use them.
Sorry, my mistake. I've amended my code to supply ints instead of shorts.
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?
Your description has both 'short' and 'Short' types which is
confusing. Reference types can be tested for using the instanceof
operator.
------------------------------8<------------------------------------
public class ShortIntegers {
public static void main(String[] args) {
SpinnerNumberModel snm = new SpinnerNumberModel(
(short)1, (short)1, (short)20, (short)1);
Object o = snm.getValue();
if (o instanceof Short) { System.out.println("Short"); }
if (o instanceof Integer) { System.out.println("Integer"); }
System.out.println(o);
}
}
------------------------------8<------------------------------------
Integer
1
Sorry for not properly distinguishing between 'short' and 'Short' and
'int' and 'Integer'. I was a little confused myself. instanceof looks
like it will do what I want. Thanks!
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.
Which factors are beyond your control?
According to Lew, getValue() in JSpinner could return various sorts of
Numbers. However, the code I use to handle the Number returned by
getValue() needs to know what it is getting back. At least I think it
does. I'm going to reread Lew's reply again now; something he said there
seemed to take me in the right direction but I just have to think on that
a bit more.
--
Rhino