JAVA_Practice_1日历

运用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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值