我使用传统的
MVC
结构,设计了
3
个类。(具体代码和工程见附件)
CalendarViewer.java
主要处理
UI
,沿用了已有代码,整理之并抽出业务逻辑,使其专注于显示层处理。
CalendarViewer.java
public
class
CalendarViewer
extends
JWindow
implements
ActionListener {
JPanel
calendarYmPanel
=
null
;
JButton
leftButton
=
new
JButton(
"<<"
);
JButton
rightButton
=
new
JButton(
">>"
);
Label
yearLabel
=
new
Label();
Label
monthLabel
=
new
Label();
Label
passedDaysLabel
=
new
Label();
JPanel
calendarWdPanel
=
null
;
//
是
caledar_week
和
calendar_days
的总包容体
JPanel
calendarWeekPanel
=
null
;
//
针对周列的布局
JPanel
calendarDaysPanel
=
null
;
//
针对日期列的布局
JPanel
calendarExitPanel
=
null
;
JButton
quitButton
=
new
JButton(
"
关闭
"
);
Border
emptyBorder
= BorderFactory.createEmptyBorder();
CalendarController
cController
=
new
CalendarController();
public
CalendarViewer() {
super
();
buildUI();
}
public
void
buildUI() {
buildTopPanel();
buildCenterPanel();
buildBottomPanel();
setLayout(
new
BorderLayout());
。。。。。。
}
private
void
buildTopPanel() {
。。。。。。
}
private
void
buildCenterPanel() {
。。。。。。
}
private
void
buildBottomPanel() {
。。。。。。
}
public
JPanel updateDaysPanel() {
。。。。。。
}
public
void
updatePassedDaysLabel() {
。。。。。。
}
public
void
actionPerformed(ActionEvent e) {
。。。。。。
}
public
static
void
main(String[] args) {
SwingUtilities.invokeLater(
new
Runnable() {
public
void
run() {
new
CalendarViewer();
}
});
}
}
|
UI
构造主要分
3
块,对应图上中下
3
个
panel
。
buildTopPanel();
buildCenterPanel();
buildBottomPanel();
事件监听的处理由下面方法完成。
actionPerformed(ActionEvent e);
基于事件的
UI
更新由以下两个方法完成。
updateDaysPanel();
updatePassedDaysLabel();
CalendarController.java
主要处理具体的业务逻辑,而所使用的一些与具体应用无关的日历算法逻辑则交给
CalendarModel.java
。
CalendarModel.java
public
class
CalendarModel {
private
int
daytab
[][] = {
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
public
boolean
isLeapYear(
int
year) {
return
((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
public
int
dayOfYear(
int
day,
int
month,
int
year) {
int
leap = isLeapYear(year) ? 1 : 0;
for
(
int
i = 1; i < month; i++)
day +=
daytab
[leap][i];
return
day;
}
public
int
daysOfMonth(
int
month,
int
year) {
int
leap = isLeapYear(year) ? 1 : 0;
return
daytab
[leap][month];
}
public
int
dayOfWeek(
int
day,
int
month,
int
year) {
if
(month == 1) {
month = 13;
year--;
}
if
(month == 2) {
month = 14;
year--;
}
return
(day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year
/ 100 + year / 400) % 7 + 1;
}
}
|
建立一个二维数组,分别表示闰年与非闰年的每月天数。主要方法有:
boolean
isLeapYear(int year);
判断闰年
dayOfYear(int day, int month, int year);
计算所提供日期为当前
year
的第几天
daysOfMonth(int month, int year);
返回当前月份的天数
dayOfWeek(int day, int month, int year);
计算某年某月某日是星期几,这里使用了基姆拉尔森计算公式。
基姆拉尔森计算公式
W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7
W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7
d
天
m 月
y 年
1 月 2 月换算为去年的 13 14 月计算
w=0 是星期一,依次类推。
m 月
y 年
1 月 2 月换算为去年的 13 14 月计算
w=0 是星期一,依次类推。
转载于:https://blog.51cto.com/zhangjunhd/127768