2013-08-22 18 views
3

我在我的外殼部件類型DateTime中,我想限制,該用戶不能選擇比實際日期更高的日期。JAVA SWT日期時間限制最大值

我搜索,但沒有像setMaximum()這樣的方法;

有人知道如何實現它嗎?

回答

4

沒有內置的方式做到這一點,但你可以自己解決問題:

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(); 
} 
+0

謝謝,我也在想這是解決方案! –

2

事實上,我沒有找到解決SWT日期時間限制的意思。

我認爲你必須將當前日期保存在一個變量中。之後,您可以使用偵聽器和getter方法來了解用戶選擇的日期。完成後,您可以執行自己的控制方法,並在出現問題時顯示彈出窗口。 (這是我的觀點 - >我沒有在我的舊的應用程序)

+0

葉氏!這是唯一可能的解決方案 –