3

I'm building a small application in netbeans,I use a JSpinner component to set the quantity of a product.How can I set the spinner to take only positive values?Is there a choice inside Netbeans that I can set or a method for the JSpinner?

EXTRA:

spinner.setModel(new SpinnerNumberModel(0, 0, 20, 1));

Community
  • 1
  • 1
giannis christofakis
  • 8,201
  • 4
  • 54
  • 65

3 Answers3

9

for JSpinner you have to implements SpinnerNumberModel

import javax.swing.*;

public class SpinnerModelTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new SpinnerModelTest().makeUI();
            }
        });
    }

    public void makeUI() {
        SpinnerModel modeltau = new SpinnerNumberModel(0.0002, 0.0001, 100.0000, 0.0001);
        JSpinner spinner = new JSpinner(modeltau);
        ((JSpinner.NumberEditor) spinner.getEditor()).getFormat().setMaximumFractionDigits(4);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(spinner);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
5

Did you try to set the Minimum ?

http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerNumberModel.html#setMinimum(java.lang.Comparable)

Yuval
  • 7,987
  • 12
  • 40
  • 54
r0ast3d
  • 2,639
  • 1
  • 14
  • 18
  • This is a link to a really old version of Java. – jzd Nov 09 '11 at 20:15
  • @jzd - yeah, I had been wondering about those many old references as well. Until I noticed that they come up very high (I remember even as first, cannot reproduce it right now - searching for 'JSpinner' 1.4.2 is second in the list) in a google search. – kleopatra Nov 10 '11 at 09:54
  • Yes some of the older API's are high on Google's results but I think that is just because there are so many links on the web pages that goolge crawls that point to the old APIs. – jzd Nov 10 '11 at 12:27
1

It works with r0ast3d's library reference:

((SpinnerNumberModel) mySpinner.getModel()).setMinimum(0);
Community
  • 1
  • 1
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185