//顯示在屏幕上的當前日期 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