防止jSpinner中的负值

时间:2012-12-18 21:46:47

标签: java swing netbeans jspinner changelistener

我正在使用netbeans在java中构建gui应用程序。它有一个jSpinner。我将其最小值设置为0.当我运行并单击向下箭头按钮时,我得到了,negativearraysizeexception。任何解决方案?

//此代码在netbeans中自动生成

protected void fireStateChanged() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
        if (listeners[i] == ChangeListener.class) {
            if (changeEvent == null) {
                changeEvent = new ChangeEvent(this);
            }
            ((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
        }
    }
}

2 个答案:

答案 0 :(得分:4)

尝试这种方式而不是NetBeans自动生成的代码:

import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Spinner {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Spinner demo");
               //10 is init value, 0 is minimum, 20 maximum and 1 is step
                SpinnerModel model = new SpinnerNumberModel(10, 0, 20, 1);
                JSpinner spinner = new JSpinner(model);
                spinner.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent e) {
                        JSpinner s = (JSpinner)e.getSource();
                        int val = (int)s.getValue();
                        System.out.println(val);
                    }
                });

                frame.add(spinner);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

返回正确的值。没有负面的。祝你好运!

答案 1 :(得分:2)

它有点晚了,但这是Netbeans中的一个自动生成代码的解决方案: jSpinner - >属性 - >第二排"型号"点击[..],你有不同的选择:)