Java Swing - Problem in JSpinner
I am developing a Java Desktop Application and designing the GUI with the help of Netbeans Swing GUI builder.
I want to use a JSpinner
in my app. I have dragged and dropped it to a JPanel
. Now, I want to set its two properties:开发者_StackOverflow
First, It should display numbers in the range of 1 to 50. Neither less than 1 nor greater than 50. How can I set that range?
Second, when I try to get the value of it by
spinner.getValue()
it returns anObject
. As my spinner's data type is Integer, would it be better to downcast theObject
intoInteger
or Is there any other way to get that numeric value?
Create a SpinnerNumberModel, this should solve all your problems.
SpinnerNumberModel model =
new SpinnerNumberModel(int initialValue, int minValue, int maxValue, int step)
For further information I recommend reading How to Use Spinners
From here, the way to do this in NetBeans:
- Create the JSpinner, as you have done.
- Right click on it and select "Customize Code"
- Set the initialization to be a spinner with a SpinnerNumberModel.
int myInt = (Integer)mySpinner.getValue();
Java has autoboxing for primitive data types, so the above code will get your spinner value as an integer, as long as you use the SpinnerNumberModel as suggested by Ham.
Ham is correct on your first question (how to limit the range of 1 to 50). For the second question, yes, you can simply cast it. Most (if not all) swing components return an Object for their value (the only notable exception being text fields).
Read the section from the Swing tutorial on "How to Use Spinners". And don't forget to check out the rest of the table of contents for Swing basics.
精彩评论