2011-10-14 56 views
0

我想在eclipse中开发Java SWT应用程序。 我需要在单击按钮时使用SWT中的DateTime日历填充文本框。 我尝试了以下代码,但无法看到日历,尽管它已创建。 任何帮助,将不胜感激。 感谢如何在Java SWT中单击按钮时弹出日历?

public void createPartControl(final Composite parent) { 
     Button button; 
     Label label; 
     final Display dev = parent.getDisplay();   
     Image image = new Image(dev,"C:\\Users\\rm186021\\Desktop\\Calendar.gif"); 
     GridLayout gridLayout = new GridLayout(); 
     gridLayout.numColumns = 3; 
     parent.setLayout(gridLayout);  
     label = new Label(parent, SWT.NULL); 
     label.setText("Start date "); 
final Text start = new Text(parent, SWT.SINGLE | SWT.BORDER); 
Button calButton = new Button(parent, SWT.PUSH); 
     calButton.setImage(image); 
     calButton.addSelectionListener(new SelectionAdapter() { 
       @Override  
       public void widgetSelected(SelectionEvent e) { 
       final Display display = new Display(); 
       final Shell shell2 = new Shell(display); 
       shell2.addListener(SWT.CALENDAR, new Listener() { 
       public void handleEvent(Event event) { 
       final DateTime calendar = new DateTime(shell2,SWT.CALENDAR | SWT.POP_UP); 
       calendar.addSelectionListener (new SelectionAdapter() { 
        public void widgetSelected (SelectionEvent e) { 
         start.setData(" " + calendar.getYear() + "-" + (calendar.getMonth() + 1) + "-" + calendar.getDay()); 
         System.out.println(start.getData()); 
         //calendar.dispose();     
        } 
       }); 
       } 
       }); 
      } 
     }); 

回答

2

DateTime真的不应该用这样的代码来创建:)试试这个:

calButton.addSelectionListener(new SelectionAdapter() { 
    @Override 
    public void widgetSelected(SelectionEvent e) { 
     final Shell shell2 = new Shell(dev.getActiveShell()); 
     // new Display() won't work on many platforms if one already exists 
     final DateTime calendar = new DateTime(shell2, SWT.CALENDAR); 
     // no need to add a listener to shell2, and POP_UP doesn't work for DateTime 
     calendar.addSelectionListener(...); 
     shell2.open(); 
     // Edward Thomson noticed it wasn't called, I missed it 
    } 
}; 
2
  1. 你要创建一个Shell,但从来没有打开它。尝试拨打shell2.open()

  2. 您正在为Shell添加SWT.CALENDAR听众。这不会做你想做的事情。或者任何事情,对于这个问题,因为Shell不会触发SWT.CALENDAR事件。相反,只需将DateTime添加到容器中,并将选择监听器连接到Calendar即可。

  3. SWT.POP_UP对于Calendar不是合适的样式位。

我会建议子类Dialog(称其为CalendarDialog,例如),设置就可以了FillLayout,加入Calendar它和挂钩听众的方式。然后致电CalendarDialog.open()

相关问题