简体   繁体   English

JAVA SWT DateTime限制最大值

[英]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. 我在我的Shell小部件类型DateTime中,我想限制,用户不能选择比实际日期更高的日期。

I searched but there is no such method like setMaximum(); 我搜索但没有像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. 实际上,我没有找到修正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. 之后,您可以使用侦听器和getter方法来了解用户选择的日期。 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) (这是我的观点 - >我在我的旧申请中这样做了)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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