-1

Given the following code, how do I store the selected value from the spinner in thickness1?

JSpinner thickn=new JSpinner();
thickn = new JSpinner(new SpinnerNumberModel(1, 1, 60, 1));      
thickn.setFont(new Font("Arial Sans-seriff", Font.BOLD, 12));
thickn.setBounds(120,105,100,25); 
// ...
int thickness1 = (Integer) thickn.getValue();

Is there an code I can add at the 3 dot region to retrieve the value from the spinner?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • I would generally keep a reference to the number model rather than the spinner. That makes getting the value simpler. **Other tips:** 1) `new Font("Arial Sans-seriff", ..)` There is no such font on any platform. Serif has only one 'f'. But there is no Arial on most Mac OS systems, and users would expect Helvetica in any case. Use [`Font.SANS_SERIF`](https://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/java/awt/Font.html#SANS_SERIF) for the best sans serif variant for all platforms. 2) `thickn.setBounds(120,105,100,25);` Oh boy.. Java GUIs have to work on different OS', screen size.. – Andrew Thompson Jan 14 '21 at 14:11
  • 1
    .. screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 4) It looks like the value is being tested at the end of the same code block, rather the on change. Use a `ChangeListener` to know **when** to get it. – Andrew Thompson Jan 14 '21 at 14:12

1 Answers1

0

In your last line, try

int thickness1 = ((SpinnerNumberModel)thickn.getModel()).getNumber().intValue();

If you want to be more explicit, you can add the following where you have the three dots, it will do the same thing as the line above

SpinnerModel model = thickn.getModel();
SpinnerNumberModel numberModel = (SpinnerNumberModel)model;
Number number = numberModel.getNumber();
int thinkness1 = number.intValue();
Kirit
  • 305
  • 1
  • 3
  • 8
  • Dear @kirit, thanks for the help but it is always taking the initial value of the spinner that is, 1 in this case. I think , the problem is that it is not the storing the value input by the user using the spinner. – just0101things Jan 14 '21 at 13:14
  • 1
    Ok, try adding the line `thickn.commitEdit();` just before the line where you call `thickn.getValue()` – Kirit Jan 14 '21 at 13:34