JSpinner time range + HH:MM format

為{幸葍}努か 提交于 2020-01-04 06:54:21

问题


I'm trying to set a JSpinner to run from hour 00:00 to 02:00.

So I built this code:

import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;


public class HourSpinner2 extends javax.swing.JFrame {


    javax.swing.JSpinner jSpinner2;

    public HourSpinner2() {

        jSpinner2 = new javax.swing.JSpinner();
        add(jSpinner2);

// Option 1 : set range

jSpinner2.setModel(new SpinnerDateModel(new java.util.Date(1388498400000L), new java.util.Date(1388484000000L), new java.util.Date(1388505600000L), java.util.Calendar.MINUTE));

//  Option 2 : set HH:mm format 

jSpinner2.setModel(new SpinnerDateModel(new java.util.Date(1388498400000L), null, null, java.util.Calendar.MINUTE));
            JSpinner.DateEditor de = new JSpinner.DateEditor(jSpinner2, "HH:mm");
            de.getTextField().setEditable( false );
            jSpinner2.setEditor(de);

    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new HourSpinner2().setVisible(true);
            }
        });
    }

 }

What I find out is that I can do only one of the 2 at a time. Either set a range or set a format. Doing both would simply freeze the component for user edit.

How to make this work for both range and format?


回答1:


The issue with your code is that actually the formatter throws away the date fields and keeps only the time part of the current value. But then the value no longer lies between min and max and this is not changeable.

As a simple workaround you may specify the min and max values as in the following code:

Calendar cal1 = GregorianCalendar.getInstance();
cal1.clear();
cal1.set(1970, Calendar.JANUARY, 1, 0, 0);
Date min = cal1.getTime();

Calendar cal2 = GregorianCalendar.getInstance();
cal2.clear();
cal2.set(1970, Calendar.JANUARY, 1, 2, 0);
Date max = cal2.getTime();


来源:https://stackoverflow.com/questions/20859045/jspinner-time-range-hhmm-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!