JSpinner without negative values

2019-05-24 06:36发布

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));

3条回答
迷人小祖宗
2楼-- · 2019-05-24 06:42

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);
    }
}
查看更多
混吃等死
4楼-- · 2019-05-24 06:43

It works with r0ast3d's library reference:

((SpinnerNumberModel) mySpinner.getModel()).setMinimum(0);
查看更多
登录 后发表回答