//显示在屏幕上的当前日期 private final Calendar today = Calendar.getInstance();
下面便开始处理点击不同天的事件。我采用比较轻易实现的外观即将天天都以一个标签是日期的按纽显示在屏幕上,我定义了一个简单的监听对象并加载到每个按纽中。由监听对象获取按纽标签值,由标签值可以得到日期与日历的位置,然后它将从日历中获取日期对象并且将日期字符串发送给监听器(通过调用fire_ActionEvent()的方式)。 //一个监听器适合所有calendar事件 private final Button_handler day_listener = new Button_handler();
private class Button_handler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("D")) { String text = ((JButton) e.getSource()).getText();
if(text.length() > 0) // <=0 means click on blank square. Ignore. { calendar.set ( calendar.get(Calendar.YEAR), // Reset the calendar calendar.get(Calendar.MONTH), // to be the chosen Integer.parseInt(text) // date. ); selected = calendar.getTime(); fire_ActionEvent( SELECT_ACTION, selected.toString() ); } } } }
// The buttons that comprise the calendar are in a single // dimensioned array that was added to a 6x7 grid layout in // order. Because of the linear structure, it's easy to // lay out the calendar just by changing the labels on // the buttons. Here's the algorithm used below: // // 1) Find out the offset to the first day of the month. // 2) Clear everything up to that offset. // 3) Add the days of the month. // 4) Clear everything else.
int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR);
fire_ActionEvent( CHANGE_ACTION, months[month] + " " + year );
calendar.set( year, month, 1 ); // First day of the current month.
int first_day_offset = calendar.get(Calendar.DAY_OF_WEEK); /* 1 */
// Note that we break out of the previous loop with i positioned // at the last day we added, thus the following ++ *must* be a // preincrement because we want to start clearing at the cell // a