我正在尝试在eclipse中开发Java SWT应用程序。 我需要在单击按钮时使用SWT中的DateTime日历填充文本框。 我尝试了以下代码,但无法看到日历,尽管它已创建。 任何帮助,将不胜感激。 感谢
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();
}
});
}
});
}
});
答案 0 :(得分: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
}
};
答案 1 :(得分:2)
您正在创建Shell
,但从未打开它。尝试拨打shell2.open()
。
您正在为SWT.CALENDAR
添加Shell
听众。这不会做你想做的事。或者其他任何事情,因为Shell
不会触发SWT.CALENDAR
事件。相反,您只需将DateTime
添加到容器中,并将选择侦听器连接到Calendar
。
SWT.POP_UP
不适合Calendar
。
我建议继承Dialog
(例如,将其称为CalendarDialog
),在其上设置FillLayout
,向其添加Calendar
并以此方式连接侦听器。然后拨打CalendarDialog.open()
。