简体   繁体   中英

JAVA SWT DateTime limit maximum

I have in my Shell widget type DateTime, I would like to limit, that user cannot choose higher date than actual date.

I searched but there is no such method like setMaximum();

Does anybody know how to achieve it ?

There is no built-in way to do this, but you can solve it yourself:

private static Date maxDate;
private static SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

public static void main(String[] args)
{
    Display display = Display.getDefault();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(1, true));

    /* Set the maximum */
    Calendar cal = Calendar.getInstance();
    cal.set(2014, 0, 0);
    maxDate = cal.getTime();

    final DateTime date = new DateTime(shell, SWT.DATE | SWT.DROP_DOWN);

    /* Listen for selection events */
    date.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            /* Get the selection */
            int day = date.getDay();
            int month = date.getMonth() + 1;
            int year = date.getYear();

            System.out.println(day + "/" + month + "/" + year);

            /* Parse the selection */
            Date newDate = null;
            try
            {
                newDate = format.parse(day + "/" + month + "/" + year);
            }
            catch (ParseException e)
            {
                return;
            }

            System.out.println(newDate);

            /* Compare it to the maximum */
            if(newDate.after(maxDate))
            {
                /* Set to the maximum */
                Calendar cal = Calendar.getInstance();
                cal.setTime(maxDate);
                date.setMonth(cal.get(Calendar.MONTH));
                date.setDay(cal.get(Calendar.DAY_OF_MONTH));
                date.setYear(cal.get(Calendar.YEAR));
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

Indeed, I didn't find the mean to fix limit for the date time in SWT.

I think you have to save the current date in a variable. After that, you can use a listener and the getter methods to know which date the user chooses. To finish, you can execute your own control method and show a pop up if there is a problem. (It's my point of view --> i did that in my old application)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM