在wicket框架下生成年份与月份DropDownChoice下拉框

来源:互联网 发布:mmd动作数据怎么做 编辑:程序博客网 时间:2024/05/22 10:42

生成一个年份与月份的下拉框,并且获取每次选中的值。

Html代码:

 <select wicket:id="selectYear"></select> <select wicket:id="selectMonth"></select>

因为年份与月份数字比较常规,所以我们可以自己写方法来填充选择框的值。
Java代码:

class Page{    //年份下拉框    private DropDownChoice<Integer> yearSelect;    //月份下拉框    private DropDownChoice<Integer> monthSelect;    //定义存储选择的年份,月份    private int selectedYear;    private int selectedMonth;    public Page(){        //年份下拉框初始化        yearSelect=createYearSelect("selectYear");        //月份下拉框初始化        monthSelect=createMonthSelect("selectMonth");        //加载到页面        this.add(yearSelect);        this.add(monthSelect);    }    //年份与月份的生成方法    //编写年份的生成方法    private DropDownChoice createYearSelect(String id){        //建立存储年份的列表        ArrayList<Integer> yearList=new ArrayList<Integer>();        //利用Calender类的方法,获取年份时间        Calendar cal = Calendar.getInstance();        //获取当前年份        int currentYear=cal.get(Calendar.YEAR);        //设置年份限度为5年        int startYear=currentYear-4;        //将年份加入ArrayList中去        for(int i=currentYear;i>=startYear;i--){            yearList.add(i);        }        final  DropDownChoice yearSelect=new DropDownChoice(id,new Model<Integer>(),yearList);        //当发生改变时,将选中年份赋值        yearSelect.add(new AjaxFormComponentUpdatingBehavior("onChange") {            protected void onUpdate(AjaxRequestTarget target) {                //当选择框内容发生改变时,捕获到选择的内容,并且转换成int保存                selectedYear = Integer.parseInt(yearSelect.getModelObject().toString());            }        });        yearSelect.setRequired(true);        yearSelect.setOutputMarkupId(true);        //默认载入当前年份        yearSelect.setModelObject(currentYear);        //初始选中项        selectedYear = currentYear;        return yearSelect;    }    //编写月份的生成方法    private DropDownChoice createMonthSelect(String id){        //创建月份列表        ArrayList<Integer> monthList=new ArrayList<Integer>();        //依次存储月份到列表        for(int i=1;i<13;i++){            monthList.add(i);        }        //获取时间的方法        Calendar cal=Calendar.getInstance();        int currentMonth=cal.get(Calendar.MONTH)+1;        //创建DropDownChoice对象,最终返回        final DropDownChoice monthSelect=new DropDownChoice(id,new Model(),monthList);        //获取当前选中的月份操作        monthSelect.add(new AjaxFormComponentUpdatingBehavior("onChange") {            protected void onUpdate(AjaxRequestTarget target) {                selectedMonth = Integer.parseInt(monthSelect.getModelObject().toString());            }        });        monthSelect.setRequired(true);        monthSelect.setOutputMarkupId(true);        //默认载入当前月份        monthSelect.setModelObject(currentMonth);        //初始选中项        selectedMonth=currentMonth;        return monthSelect;    }}
原创粉丝点击