/*
* 2012年5月13日10:37:58
* 日历程序
* Function:
* 显示当前月份的日历
* 总结
* 1. 0-11分别代表1-12月
* 1-7分别代表周日-周六
* 2. 使用GregorianCalendar对象的get方法(参数)获取月,日,年等信息
* 3.
*/
import java.text.DateFormatSymbols
import java.util.*
public class CalendarTest {
public static void main(String[] args) {
//construct d as current date构造一个日期
GregorianCalendar d = new GregorianCalendar()
//获取今天是这个月的第几天
int today = d.get(Calendar.DAY_OF_MONTH) //Calendar.DAY_OF_MONTH作为参数调用,得到今天是这个月的第几天
int month = d.get(Calendar.MONTH) //月份
d.set(Calendar.DAY_OF_MONTH, 1) //设置d的日期是本月的1号
int weekDay = d.get(Calendar.DAY_OF_WEEK) //获取当天位于本星期的第几天,也就确定了星期几,值的范围是1-7
int firstDayOfWeek = d.getFirstDayOfWeek() //获取一星期的第早坦一天,我们得到的是Calendar.SUNDAY,因为我们一星期的第一天是周日
int indent = 0 //为了定位本月第一天,定义索引
while (weekDay != firstDayOfWeek) {
//注意,月份用0-11代表1-12月,为了清晰起见,使用常量代替,下面宽迟获取月份得到的实际是当前月-1的值,所以我们要加1
//System.out.printf("当前星期的第%d天,位于当月的第%d天, 现在是%d月\n",
//weekDay, d.get(Calendar.DAY_OF_MONTH), d.get(Calendar.MONTH)+1) //Test Code
indent++//陆巧桐缩进个数+1
d.add(Calendar.DAY_OF_MONTH, -1)//当前天数-1,如果现在是1号,则执行本条代码后,时间变为上一个月最后一天
weekDay = d.get(Calendar.DAY_OF_WEEK) //重新获取当天位于本星期的第几天
}
String[] weekDayNames = new DateFormatSymbols().getShortWeekdays()//获取简短形式的星期字符串数组
//System.out.println(weekDayNames.length)getShortWeekdays()得到的数组的长度是8,下标为0的是没有值1为星期日...7为星期六
//注释代码1
//Java核心技术的代码
/*
do {
//System.out.printf("%4s", weekDayNames[weekDay]) //经过上面定义索引,weekDay代表的是本星期日
d.add(Calendar.DAY_OF_MONTH, 1) //天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK) //重新获得weekDay的值
} while (weekDay != firstDayOfWeek) //当循环完一个星期后,这里判断不成立,退出循环
*/
//我写的代码,替换上面注释代码1
for (int i=1i<weekDayNames.lengthi++)//打印星期标题
System.out.printf("%3s\t", weekDayNames[i])//引号内是一个全角的空格,因为是中文版,不是书上英文环境,中文和空格对于不上,这里我们用\t解决
//System.out.printf("%3s ", weekDayNames[i]) //方式2
System.out.println()//换行
for (int i=1i<=indenti++)//确定一星期的一天位置,利用上面indent
System.out.printf("\t")//如用方式2,则这里内容是四个全角空格
//实现输出日期
d.set(Calendar.MONTH, month)
d.set(Calendar.DAY_OF_MONTH, 1)
do {
//print day
int day = d.get(Calendar.DAY_OF_MONTH)
System.out.printf("%3d", day)
if (day == today)
System.out.print("*")
System.out.print("\t")
d.add(Calendar.DATE, 1)//天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK)//刷新weekDay
if (weekDay == firstDayOfWeek) //如果这天等于星期天则换行
System.out.println()
} while (d.get(Calendar.MONTH) == month)
}
}
随便做了一个,其实一楼网友说的判断哪些30天,是否闰年什么的没必要,看代码:
package com.baidu.calendarimport java.awt.BorderLayout
import java.awt.Color
import java.awt.FlowLayout
import java.awt.Font
import java.awt.GridLayout
import java.awt.event.ItemEvent
import java.awt.event.ItemListener
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import javax.swing.JComboBox
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.border.CompoundBorder
import javax.swing.border.EmptyBorder
import javax.swing.border.LineBorder
public class CalendarInterface extends JFrame {
private static final long serialVersionUID = 1L
private JComboBox yearBox, monthBox
private static final int YEAR_RANGE = 50 // 年份范围,即往前往后各推多少年
private JPanel topPane, contentPane
private JPanel bottomPane, bottomTopPane, mainPane
private JLabel dateLabel
private boolean init = false
private Calendar cal
private static final Calendar NOW = Calendar.getInstance()
private static final String[] DAY_OF_WEEK = {"星期日弯让", "星期一", "星期二",
"星期三"虚磨, "星期四", "星期五", "星期六"}
private DateFormat df = new SimpleDateFormat("yyyy年MM月")
private static final Color FONT_GRAY = new Color(0xaa, 0xaa, 0xaa)
private static final int DATE_GRAY = -1
private static final int DATE_RED 差闹斗= 1
private static final int DATE_BLACK = 0
public CalendarInterface() {
super("日历")
cal = Calendar.getInstance()
cal.setFirstDayOfWeek(Calendar.SUNDAY)
}
public void launch() {
setVisible(true)
setSize(600, 450)
setDefaultCloseOperation(EXIT_ON_CLOSE)
// 主面板
contentPane = new JPanel(new BorderLayout())
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5))
contentPane.setBackground(Color.WHITE)
// 顶部选择日期和月份的区域
topPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 0)) // 居中对齐,控件间隔50px
topPane.setBorder(new EmptyBorder(0, 0, 10, 0)) // 底部空出10px
topPane.setBackground(Color.WHITE)
// 底部显示星期条和日历列表区域
bottomPane = new JPanel(new BorderLayout())
bottomPane.setBorder(new LineBorder(Color.BLACK, 1))
// 星期条
bottomTopPane = new JPanel(new GridLayout(1, 7))
bottomTopPane.setBackground(new Color(0x55, 0x55, 0x55))
// 日期列表
mainPane = new JPanel()
mainPane.setLayout(new GridLayout(0, 7)) // 列数为7,行数自动填充
for(int i = Calendar.SUNDAY i <= Calendar.SATURDAY i ++) {
bottomTopPane.add(createDay(DAY_OF_WEEK[i - 1]))
}
bottomPane.add(bottomTopPane, BorderLayout.NORTH) // 星期栏放在顶部
// 年份下拉列表
yearBox = new JComboBox()
int currentYear = cal.get(Calendar.YEAR)
// 年份范围为往前往后各推50年
for(int i = currentYear - YEAR_RANGE i < currentYear + YEAR_RANGE + 1 i ++) {
yearBox.addItem(i)
}
yearBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(ItemEvent.SELECTED == e.getStateChange()) {
reset() // 选择后刷新布局
}
}
})
yearBox.setSelectedIndex(YEAR_RANGE) // 默认选中当前年份
String months[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}
// 月份下拉列表
monthBox = new JComboBox(months)
monthBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(ItemEvent.SELECTED == e.getStateChange()) {
reset() //刷新布局
}
}
})
monthBox.setSelectedIndex(cal.get(Calendar.MONTH)) // 选择当前月份
// 显示当前年月的控件
this.dateLabel = new JLabel(df.format(cal.getTime()))
topPane.add(yearBox)
topPane.add(monthBox)
topPane.add(dateLabel)
contentPane.add(topPane, BorderLayout.NORTH)
bottomPane.add(mainPane, BorderLayout.CENTER)
contentPane.add(bottomPane, BorderLayout.CENTER)
setContentPane(contentPane)
validate()
init = true // 初始化完成
reset() // 刷新界面
setLocationRelativeTo(null) // 居中显示
}
public static void main(String[] args) {
new CalendarInterface().launch()
}
private void reset() { // 每次年份或月份改变后则日历重新排列
if(!init) { // 若未初始化则返回,避免设置默认年月时调用此方法出错
return
}
int year = (Integer) yearBox.getSelectedItem()
int month = Integer.parseInt((String) monthBox.getSelectedItem())
// 将日期设置为本月第一天
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month - 1)
cal.set(Calendar.DATE, 1)
dateLabel.setText(df.format(cal.getTime())) // 显示年月
mainPane.removeAll() // 清空日历列表
// 判断本月第一天是星期几,在第一天之前增加空的日历
int startDayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
int i
// 先设置为本周属于上个月的几天,置灰显示
cal.add(Calendar.DATE, -(startDayOfWeek - Calendar.SUNDAY) - 1)
for(i = Calendar.SUNDAY i < startDayOfWeek i ++) {
cal.add(Calendar.DATE, 1)
int date = cal.get(Calendar.DATE)
mainPane.add(createDate(Integer.toString(date), DATE_GRAY))
}
i = startDayOfWeek
// 重新初始化为本月第一天
cal.set(Calendar.MONTH, month - 1)
cal.set(Calendar.DATE, 1)
int maxDate = cal.getActualMaximum(Calendar.DATE) // 本月最多的天数(不用再去判断是否闰年了)
for(int j = 1 j <= maxDate j ++) {
cal.set(Calendar.DATE, j) // 日期一直自增,用来判断是否是今天
JLabel jlDate = null
if(isToday()) { // 是今天则高亮显示
jlDate = createDate(Integer.toString(j), DATE_RED)
} else { // 不是今天则显示为普通颜色
jlDate = createDate(Integer.toString(j))
}
mainPane.add(jlDate)
}
// 最后一周把不属于本月的几天用灰色控件填充
int lastDay = cal.get(Calendar.DAY_OF_WEEK)
for(i = lastDay i < Calendar.SATURDAY i ++) {
cal.add(Calendar.DATE, 1)
int date = cal.get(Calendar.DATE)
mainPane.add(createDate(Integer.toString(date), DATE_GRAY))
}
mainPane.validate()
}
private JLabel createDate(String date) {
return createDate(date, DATE_BLACK)
}
// 创建日期控件
private JLabel createDate(String date, int dateColor) {
JLabel label = new JLabel(date, JLabel.CENTER)
CompoundBorder border = new CompoundBorder(
new LineBorder(Color.WHITE, 1),
new EmptyBorder(10, 10, 10, 10))
label.setBorder(border)
Font font = new Font("Arial", Font.BOLD, 30)
if(DATE_GRAY == dateColor) { // 如果不是本月则文字置灰
label.setForeground(FONT_GRAY)
} else if(DATE_RED == dateColor) { // 如果是今天则高亮显示
label.setForeground(Color.RED)
}
label.setFont(font)
return label
}
// 创建星期几的横条
private JLabel createDay(String day) {
JLabel jlDay = new JLabel(day, JLabel.CENTER)
jlDay.setBorder(new EmptyBorder(5, 5, 5, 5))
jlDay.setBackground(Color.GRAY)
jlDay.setForeground(Color.WHITE)
return jlDay
}
// 判断是否今天
private boolean isToday() {
return cal.get(Calendar.YEAR) == NOW.get(Calendar.YEAR)
&& cal.get(Calendar.MONTH) == NOW.get(Calendar.MONTH)
&& cal.get(Calendar.DATE) == NOW.get(Calendar.DATE)
}
}
修改部分见注释
如派旦 public static void main(String[] args){
System.out.println(" 日 一 二 三 四 五 六")
Calendar rili = Calendar.getInstance()
rili.set(2011, 3, 1)
int xingqi = rili.get(Calendar.DAY_OF_WEEK) - 1
String a[] = new String[xingqi + 30]
羡轮 for (int i = 0 i < xingqi i++)
{
a[i] = "**"
}
for (int i = xingqi, n = 1 i < xingqi + 30 i++)
{
if (n <= 9)
a[i] = String.valueOf(n) + " "
else
a[i] = String.valueOf(n)
n++
}
//a[i]的i从0开始,你下面从1开始循,自然少了第一个
for (int i = 0 i < a.length i++)
{
//遇到星期六应该是先打印日期,再换行,你之前是先换行,再打星期六
System.out.print(" 渣扰 " + a[i])
//改了循环起始位置,此处改为i+1
if ((i + 1)% 7 == 0)
{
System.out.println(" ")
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)