运用Swing实现了一个获取系统当前时间然后显示当月日历的小程序。
Calendar.getInstance()用于获取当前时间,使用GridLayout将间隔设置为0,完成布局。
注意闰年。
public class MyCalendar {
static int dayOfMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
static String weekday[] = {"日","一","二","三","四","五","六"};
static boolean ifLeapYear(int year)
{
if(year%4 == 0)
{
if(year%100 == 0)
{
if(year%400 == 0)
return true;
else
return false;
}
else
return true;
}
return false;
}
static void myCalendar()
{
int year,month,day,week;
Calendar cal=Calendar.getInstance();
year=cal.get(Calendar.YEAR);
month=cal.get(Calendar.MONTH) + 1;
day=cal.get(Calendar.DATE);
week = cal.get(Calendar.DAY_OF_WEEK);
int weekOfFirstDay = (7 + week - day % 7) % 7;
JFrame calendar = new JFrame();
calendar.setTitle(""+year+"年"+month+"月日历");
Container c = calendar.getContentPane();
calendar.setLayout(new GridLayout(6,7,0,0));
for(int i = 0;i<7;i++)
c.add(new JButton(weekday[i]));
for(int i = 0;i<weekOfFirstDay;i++)
c.add(new JButton());
for(int i = 0;i<dayOfMonth[month] - weekOfFirstDay;i++)
c.add(new JButton(""+(i+1)));
if(month == 2 && ifLeapYear(year))
{
c.add(new JButton("29"));
for(int i = 0;i<=35 - dayOfMonth[month] - weekOfFirstDay - 1;i++)
c.add(new JButton());
}
else
{
for(int i = 0;i<=35 - dayOfMonth[month] - weekOfFirstDay;i++)
c.add(new JButton());
}
calendar.setSize(400,300);
calendar.setVisible(true);
}
public static void main(String[] args) {
myCalendar();
}
}