按照你的要求编写的Java日历验证程序如下
UI.java
import?java.util.Scanner;
public?class?UI?{
static?Scanner?sc=new?Scanner(System.in);
public?static?int?askInt(String?s){
System.out.print(s);
return?sc.nextInt();
}
public?static?void?println(String?s){
System.out.println(s);
EE.java
public?class?EE?{
public?void?validateDateCore(){
int?year?=UI.askInt("Enter?the?year:?");
int?month=UI.askInt("Enter?the?month:?");
int?day=UI.askInt("Enter?the?day:?");
if(year?1){
UI.println("The?year?is?not?a?valid?number.");
return;
UI.println("The?month?is?not?a?valid?number.");
int?monthDay=0;
switch(month){
case?1:
case?10:
}else{
break;
if(day1?||?daymonthDay){
UI.println("The?day?is?not?a?valid?number.");
UI.println("It?is?"+day+"/"+month+"/"+year+".");
public?static?void?main(String[]?args)?{
new?EE().validateDateCore();
运行结果
我给你贴上我在java核心技术中看到的代码吧,当然没有输入年份和月份,是按照当前时间创建的,写有我写的注释,应该能看的懂
/*
* 日历程序
* Function:
* 显示当前月份的日历
* 总结
*/
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 firstDayOfWeek = d.getFirstDayOfWeek(); //获取一星期的第一天,我们得到的是Calendar.SUNDAY,因为我们一星期的第一天是周日
int indent = 0; //为了定位本月第一天,定义索引
while (weekDay != firstDayOfWeek) {
//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();//获取简短形式的星期字符串数组
//注释代码1
//Java核心技术的代码
do {
d.add(Calendar.DAY_OF_MONTH, 1); //天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK); //重新获得weekDay的值
} while (weekDay != firstDayOfWeek); //当循环完一个星期后,这里判断不成立,退出循环
//我写的代码,替换上面注释代码1
for (int i=1; iweekDayNames.length; i++)//打印星期标题
System.out.println();//换行
for (int i=1; i=indent; i++)//确定一星期的一天位置,利用上面indent
//实现输出日期
d.set(Calendar.MONTH, month);
d.set(Calendar.DAY_OF_MONTH, 1);
//print day
int day = d.get(Calendar.DAY_OF_MONTH);
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);
详细代码
//CalendarWindow类:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class CalendarWindow extends JFrame implements ActionListener,
MouseListener,FocusListener{
int year,month,day;
CalendarMessage calendarMessage;
CalendarPad calendarPad;
NotePad notePad;
JTextField showYear,showMonth;
JTextField [] showDay;
CalendarImage calendarImage;
Clock clock;
JButton nextYear,previousYear,nextMonth,previousMonth;
JButton saveDailyRecord,deleteDailyRecord,readDailyRecord;
File dir;
Color backColor=Color.gray;
public CalendarWindow(){
dir=new File("./dailyRecord");
dir.mkdir();
for(int i=0;ishowDay.length;i++){
showDay[i]=new JTextField();
showDay[i].setBackground(backColor);
showDay[i].addMouseListener(this);
showDay[i].addFocusListener(this);
calendarMessage=new CalendarMessage();
calendarPad=new CalendarPad();
notePad=new NotePad();
Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date());
year=calendar.get(Calendar.YEAR);
month=calendar.get(Calendar.MONTH)+1;
day=calendar.get(Calendar.DAY_OF_MONTH);
calendarMessage.setYear(year);
calendarMessage.setMonth(month);
calendarMessage.setDay(day);
calendarPad.setCalendarMessage(calendarMessage);
calendarPad.setShowDayTextField(showDay);
notePad.setShowMessage(year,month,day);
calendarPad.showMonthCalendar();
doMark(); //给有日志的号码做标记,见后面的doMark()方法
calendarImage=new CalendarImage();
calendarImage.setImageFile(new File("sea.jpg"));
clock=new Clock();
JSplitPane splitV1=
new JSplitPane(JSplitPane.VERTICAL_SPLIT,calendarPad,calendarImage);
new JSplitPane(JSplitPane.VERTICAL_SPLIT,notePad,clock);
add(splitH,BorderLayout.CENTER);
showYear.setHorizontalAlignment(JTextField.CENTER);
showMonth.setHorizontalAlignment(JTextField.CENTER);
nextYear=new JButton("下年");
previousYear=new JButton("上年");
nextMonth=new JButton("下月");
previousMonth=new JButton("上月");
nextYear.addActionListener(this);
previousYear.addActionListener(this);
nextMonth.addActionListener(this);
previousMonth.addActionListener(this);
showYear.addActionListener(this);
JPanel north=new JPanel();
north.add(previousYear);
north.add(showYear);
north.add(nextYear);
north.add(previousMonth);
north.add(showMonth);
north.add(nextMonth);
add(north,BorderLayout.NORTH);
saveDailyRecord=new JButton("保存日志") ;
deleteDailyRecord=new JButton("删除日志");
readDailyRecord=new JButton("读取日志");
saveDailyRecord.addActionListener(this);
deleteDailyRecord.addActionListener(this);
readDailyRecord.addActionListener(this);
JPanel pSouth=new JPanel();
pSouth.add(saveDailyRecord);
pSouth.add(deleteDailyRecord);
pSouth.add(readDailyRecord);
add(pSouth,BorderLayout.SOUTH);
setVisible(true);//根据参数 b 的值显示或隐藏此 Window
validate();//验证此容器及其所有子组件
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置用户在此窗体上发起 "close" 时默认执行的操作
public void actionPerformed(ActionEvent e){
if(e.getSource()==nextYear){
year++;
showYear.setText(""+year);
doMark();
else if(e.getSource()==previousYear){
year--;
else if(e.getSource()==nextMonth){
month++;
showMonth.setText(" "+month);
else if(e.getSource()==previousMonth){
month--;
else if(e.getSource()==showYear){
String s=showYear.getText().trim();
char a[]=s.toCharArray();
boolean boo=false;
for(int i=0;ia.length;i++)
if(!(Character.isDigit(a[i])))
boo=true;
if(boo==true) //弹出"警告"消息对话框
JOptionPane.showMessageDialog(this,"您输入了非法年份","警告", JOptionPane.WARNING_MESSAGE);
else if(boo==false)
year=Integer.parseInt(s);
else if(e.getSource()==saveDailyRecord){
notePad.save(dir,year,month,day);
else if(e.getSource()==deleteDailyRecord){
notePad.delete(dir,year,month,day);
else if(e.getSource()==readDailyRecord)
notePad.read(dir,year,month,day);
public void mousePressed(MouseEvent e){
JTextField text=(JTextField)e.getSource();
String str=text.getText().trim();
try{ day=Integer.parseInt(str);
catch(NumberFormatException exp){
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void focusGained(FocusEvent e){
Component com=(Component)e.getSource();
com.setBackground(Color.red);
public void focusLost(FocusEvent e){
com.setBackground(backColor);
public void doMark(){
showDay[i].removeAll();
String str=showDay[i].getText().trim();
try{
int n=Integer.parseInt(str);
if(isHaveDailyRecord(n)==true){ //见后面的isHaveDailyRecord()方法
JLabel mess=new JLabel("存");
mess.setFont(new Font("TimesRoman",Font.PLAIN,11));
mess.setForeground(Color.black) ;
showDay[i].add(mess);
} }
catch(Exception exp){}
calendarPad.repaint();
calendarPad.validate();
public boolean isHaveDailyRecord(int n){
String key=""+year+""+month+""+n;
String [] dayFile=dir.list();
for(int k=0;kdayFile.length;k++){
if(dayFile[k].equals(key+".txt")){
} }
return boo;
public static void main(String args[]){
new CalendarWindow();
//CalendarPad类:
public class CalendarPad extends JPanel{
JLabel title[];
String [] 星期={"SUN/日","MON/一","TUE/二","WED/三","THU/四","FRI/五","SAT/六"};
JPanel north,center;
public CalendarPad(){
setLayout(new BorderLayout());
north=new JPanel();
center=new JPanel();
add(center,BorderLayout.CENTER);
title[j]=new JLabel();
title[j].setText(星期[j]);
title[j].setHorizontalAlignment(JLabel.CENTER);
title[j].setBorder(BorderFactory.createRaisedBevelBorder());
north.add(title[j]);
title[0].setForeground(Color.red);
public void setShowDayTextField(JTextField [] text){
showDay=text;
showDay[i].setHorizontalAlignment(JTextField.CENTER);
showDay[i].setEditable(false);
center.add(showDay[i]);
public void setCalendarMessage(CalendarMessage calendarMessage){
this.calendarMessage=calendarMessage;
public void showMonthCalendar(){
String [] a=calendarMessage.getMonthCalendar();
showDay[i].setText(a[i]);
validate();
import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.border.LineBorder;
/**
* @company:NEUSOFT
* @Title:日期选择控件
* @Description:在原有基础上修改了以下内容:
* 1. 将容器由Frame改为了Dialog,以便在基于对话框的程序中也能够使用
public class DateChooserJButton extends JButton {
private DateChooser dateChooser = null;
private String preLabel = "";
public DateChooserJButton() {
this(getNowDate());
public DateChooserJButton(SimpleDateFormat df, String dateString) {
this();
setText(df, dateString);
public DateChooserJButton(Date date) {
this("", date);
public DateChooserJButton(String preLabel, Date date) {
if (preLabel != null)
this.preLabel = preLabel;
setDate(date);
setBorder(null);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (dateChooser == null)
dateChooser = new DateChooser();
Point p = getLocationOnScreen();
dateChooser.showDateChooser(p);
});
private static Date getNowDate() {
return Calendar.getInstance().getTime();
private static SimpleDateFormat getDefaultDateFormat() {
return new SimpleDateFormat("yyyy年MM月dd日");
// 覆盖父类的方法
public void setText(String s) {
Date date;
try {
date = getDefaultDateFormat().parse(s);
} catch (ParseException e) {
date = getNowDate();
public void setText(SimpleDateFormat df, String s) {
date = df.parse(s);
public void setDate(Date date) {
super.setText(preLabel + getDefaultDateFormat().format(date));
public Date getDate() {
String dateString = this.getText().substring(preLabel.length());
return getDefaultDateFormat().parse(dateString);
return getNowDate();
public String getDateString()
{
Date birth =getDate();
DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
return formatDate.format(birth).toString();
//return this.getText().substring(preLabel.length());
// 覆盖父类的方法使之无效
//public void addActionListener(ActionListener listener) {
//}
private class DateChooser extends JPanel implements ActionListener,
ChangeListener {
Color backGroundColor = Color.gray; // 底色
// 月历表格配色----------------//
Color palletTableColor = Color.white; // 日历表底色
Color todayBackColor = Color.orange; // 今天背景色
Color weekFontColor = Color.blue; // 星期文字色
Color dateFontColor = Color.black; // 日期文字色
Color weekendFontColor = Color.red; // 周末文字色
// 控制条配色------------------//
Color controlLineColor = Color.pink; // 控制条底色
Color controlTextColor = Color.white; // 控制条标签文字色
Color rbFontColor = Color.white; // RoundBox文字色
Color rbBorderColor = Color.red; // RoundBox边框色
Color rbButtonColor = Color.pink; // RoundBox按钮色
Color rbBtFontColor = Color.red; // RoundBox按钮文字色
JDialog dialog;
JSpinner yearSpin;
JSpinner monthSpin;
JSpinner hourSpin;
DateChooser() {
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
private JPanel createYearAndMonthPanal() {
Calendar c = getCalendar();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH) + 1;
int currentHour = c.get(Calendar.HOUR_OF_DAY);
JPanel result = new JPanel();
result.setLayout(new FlowLayout());
result.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
result.add(yearSpin);
JLabel yearLabel = new JLabel("年");
yearLabel.setForeground(controlTextColor);
result.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
result.add(monthSpin);
JLabel monthLabel = new JLabel("月");
monthLabel.setForeground(controlTextColor);
result.add(monthLabel);
①.));
hourSpin.setName("Hour");
hourSpin.addChangeListener(this);
result.add(hourSpin);
JLabel hourLabel = new JLabel("时");
hourLabel.setForeground(controlTextColor);
result.add(hourLabel);
return result;
private JPanel createWeekAndDayPanal() {
String colname[] = { "日", "一", "二", "三", "四", "五", "六" };
// 设置固定字体,以免调用环境改变影响界面美观
result.setBackground(Color.white);
JLabel cell;
cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
cell.setForeground(weekendFontColor);
else
cell.setForeground(weekFontColor);
result.add(cell);
int actionCommandId = 0;
JButton numberButton = new JButton();
numberButton.setBorder(null);
numberButton.setHorizontalAlignment(SwingConstants.RIGHT);
numberButton.setActionCommand(String
.valueOf(actionCommandId));
numberButton.addActionListener(this);
numberButton.setBackground(palletTableColor);
numberButton.setForeground(dateFontColor);
numberButton.setForeground(weekendFontColor);
daysButton[i][j] = numberButton;
result.add(numberButton);
actionCommandId++;
private JDialog createDialog(JDialog owner) {
JDialog result = new JDialog(owner, "日期时间选择", true);
result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
result.getContentPane().add(this, BorderLayout.CENTER);
result.pack();
result.setSize(width, height);
void showDateChooser(Point position) {
JDialog owner = (JDialog) SwingUtilities
.getWindowAncestor(DateChooserJButton.this);
if (dialog == null || dialog.getOwner() != owner)
dialog = createDialog(owner);
dialog.setLocation(getAppropriateLocation(owner, position));
flushWeekAndDay();
dialog.setVisible(true);
Point getAppropriateLocation(JDialog owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + width) - (p.x + owner.getWidth());
int offsetY = (position.y + height) - (p.y + owner.getHeight());
if (offsetX 0) {
result.x -= offsetX;
if (offsetY 0) {
result.y -= offsetY;
private Calendar getCalendar() {
Calendar result = Calendar.getInstance();
result.setTime(getDate());
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
private int getSelectedHour() {
return ((Integer) hourSpin.getValue()).intValue();
private void dayColorUpdate(boolean isOldDay) {
int day = c.get(Calendar.DAY_OF_MONTH);
c.set(Calendar.DAY_OF_MONTH, 1);
if (isOldDay)
daysButton[i][j].setForeground(dateFontColor);
daysButton[i][j].setForeground(todayBackColor);
private void flushWeekAndDay() {
int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);
String s = "";
if (dayNo = 1 dayNo = maxDayNo)
s = String.valueOf(dayNo);
daysButton[i][j].setText(s);
dayNo++;
dayColorUpdate(false);
public void stateChanged(ChangeEvent e) {
JSpinner source = (JSpinner) e.getSource();
if (source.getName().equals("Hour")) {
c.set(Calendar.HOUR_OF_DAY, getSelectedHour());
setDate(c.getTime());
dayColorUpdate(true);
if (source.getName().equals("Year"))
c.set(Calendar.YEAR, getSelectedYear());
// (source.getName().equals("Month"))
c.set(Calendar.MONTH, getSelectedMonth() - 1);
JButton source = (JButton) e.getSource();
if (source.getText().length() == 0)
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
c.set(Calendar.DAY_OF_MONTH, newDay);
这是一个专门的选日期的类 ,你看看完了调用就行了
以上就是土嘎嘎小编为大家整理的java日历控件代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!