年月控制这部分分为控制按钮,月下拉列表和年Spinner(翻译为微调控制器。。。。。。。)。控制按钮没什么好说的,无非就是控制加一减一,注意边界循环就可以了。
Spinner的用法很简单,看下代码:
yearChooser
=
new
Spinner(yearMonthChooser, SWT.READ_ONLY
|
SWT.BORDER);
//初始化,只读,带边框
yearChooser.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int n = yearChooser.getSelection();
basicCalendar.set(Calendar.YEAR, n);
yearChooser.setSelection(n);
setDays();
}
});
//加上选择事件监听
yearChooser.setMaximum(3000);//设置上限
yearChooser.setMinimum(1899);//设置下限
yearChooser.setIncrement(1);//步进值
yearChooser.setPageIncrement(10);//这个是按下pageup和pagedown时的步进值
yearChooser.setSelection(basicCalendar.get(Calendar.YEAR));//选择当前年
//初始化,只读,带边框
yearChooser.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int n = yearChooser.getSelection();
basicCalendar.set(Calendar.YEAR, n);
yearChooser.setSelection(n);
setDays();
}
});
//加上选择事件监听
yearChooser.setMaximum(3000);//设置上限
yearChooser.setMinimum(1899);//设置下限
yearChooser.setIncrement(1);//步进值
yearChooser.setPageIncrement(10);//这个是按下pageup和pagedown时的步进值
yearChooser.setSelection(basicCalendar.get(Calendar.YEAR));//选择当前年
月的下拉列表看似简单实则不然,因为我们要考虑国际化的问题。
以上是中文环境和英文环境下的测试效果。关键点是:月的信息从Locale中取。以下是关键代码:
private
void
initMonth() {
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(locale);
String[] monthNames = dateFormatSymbols.getMonths();
int month = monthChooser.getSelectionIndex();
if (monthChooser.getItemCount() > 0 ) {
monthChooser.removeAll();
}
for ( int i = 0 ; i < monthNames.length; i ++ ) {
String name = monthNames[i];
if (name.length() > 0 ) {
monthChooser.add(name);
}
}
if (month < 0 ) {
month = 0 ;
} else if (month >= monthChooser.getItemCount()) {
month = monthChooser.getItemCount() - 1 ;
}
monthChooser.select(month);
}
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(locale);
String[] monthNames = dateFormatSymbols.getMonths();
int month = monthChooser.getSelectionIndex();
if (monthChooser.getItemCount() > 0 ) {
monthChooser.removeAll();
}
for ( int i = 0 ; i < monthNames.length; i ++ ) {
String name = monthNames[i];
if (name.length() > 0 ) {
monthChooser.add(name);
}
}
if (month < 0 ) {
month = 0 ;
} else if (month >= monthChooser.getItemCount()) {
month = monthChooser.getItemCount() - 1 ;
}
monthChooser.select(month);
}