自定义spinnerdatemodel没有做任何事情

时间:2015-06-29 09:02:57

标签: java swing

自定义spinnerdatemodel with overriden getPrevious()和getNext()没有做任何事情。我做错了什么?

这是我的代码。这对我来说是正确的;所以,是的,任何帮助将不胜感激。谢谢!

/**
 * Custom spinner model for the times (hhmm)
 */
class SpinnerTimeModel extends SpinnerDateModel {

    /**
     * Constructor
     */
    public SpinnerTimeModel() {
        cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        setValue(cal.getTime());
        setStart(cal.getTime());
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        setEnd(cal.getTime());
    }

    /**
     * Returns a time 30 minutes prior to the current time
     *
     * @return a time 30 minutes prior to the current time
     */
    @Override
    public Object getPreviousValue() {
        Calendar previous = Calendar.getInstance();
        previous.setTime(getDate());
        previous.add(Calendar.MINUTE, -30);
        return previous.getTime();
    }

    /**
     * Returns a time 30 minutes after the current time
     *
     * @return a time 30 minutes after the current time
     */
    @Override
    public Object getNextValue() {
        Calendar next = Calendar.getInstance();
        next.setTime(getDate());
        next.add(Calendar.MINUTE, 30);
        return next.getTime();
    }
    private Calendar cal;
}

1 个答案:

答案 0 :(得分:0)

如果将JSpinner编辑器类型设置为DateEditor,则现有代码将正常工作。代码评论。

public class spinnerdemo {
    public void show() {
        JFrame f = new JFrame("JSpinner Demo");
        f.setSize(500, 100);
        f.setLayout(new GridLayout(1, 1));
        JSpinner ctrlSpin = new JSpinner();
        ctrlSpin.addChangeListener(new javax.swing.event.ChangeListener() {
            @Override
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                System.out.println("" + ctrlSpin.getValue());
            }
        });
        ctrlSpin.setModel(new SpinnerTimeModel());
        //set the DateEditor
        ctrlSpin.setEditor(new JSpinner.DateEditor(ctrlSpin, "dd/MM/yyyy HH:mm:ss.SS"));
        f.add(ctrlSpin);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
    public static void main(String[] args) {
        new spinnerdemo().show();
    }
}